将几个相同的行转换为相同的列

时间:2018-05-11 20:22:57

标签: sql row multiple-columns

以下可能吗?

我有一个包含3列(Code,CaseNumber,Discount)的表,这6行。

123 1 10
123 2 20
123 3 30
456 4 40
456 5 50
456 6 60

如何将输出设置为Code,CaseNumber,Discount,其中“CaseNumber,Discount”会针对相同的代码重复?

例如,对于上表,输出应为

123 1 10 2 20 3 30
456 4 40 5 50 6 60

2 个答案:

答案 0 :(得分:0)

 select Code,  
 max(case when CaseNumber = 1 then CaseNumber end) as CaseNumber,
 max(case when CaseNumber = 2 then CaseNumber end) as CaseNumber,
 max(case when CaseNumber = 3 then CaseNumber end) as CaseNumber, 
 max(case when CaseNumber = 4 then CaseNumber end) as CaseNumber, 
 max(case when CaseNumber = 5 then CaseNumber end) as CaseNumber, 
 max(case when CaseNumber = 6 then CaseNumber end) as CaseNumber,
 max(case when Discount = 10 then Discount end) as Discount,
 max(case when Discount = 20 then Discount end) as Discount,
 max(case when Discount = 30 then Discount end) as Discount, 
 max(case when Discount = 40 then Discount end) as Discount, 
 max(case when Discount = 50 then Discount end) as Discount, 
 max(case when Discount = 60 then Discount end) as Discount     
 from
 (
 select * , row_number() over(partition by Code order by Code) rn
 from yourTable
 ) s
 group by Code
 go

答案 1 :(得分:0)

假设您的原始表是#temp:

declare @final table (rowid int identity, string varchar(max))

declare @holding table (Code int, CaseNumber int, Discount int, rownum int) 
insert @holding 
select *, row_number() over(partition by code order by code) from #temp 

--select * from @holding

declare @string varchar(max)=''
--declare @string2 varchar(max)=''
declare @code int = (select min(code) from @holding)
declare @casenumber int
declare @discount int
declare @iterator int = 1
while @code<=(select max(code) from @holding)
--select @string=  @code','
begin 
while @iterator<=(select max(rownum) from @holding where code=@code)
begin
select @casenumber=  casenumber , @discount=discount from @holding where code=@code and  @iterator=rownum
select @string=@string+','+cast(@casenumber as varchar(max))+','+cast(@discount as varchar(max))
set @iterator=@iterator+1
end
insert @final
select cast(@code as varchar(max))+@string
select @code=min(code) from @holding where code>@code
set @iterator=1
set @string=''
end 

set @iterator=1
set @string=''
declare @string2 varchar(max)=''
while @iterator<=(select max(rowid) from @final)
begin
select @string2 = string from @final where rowid=@iterator
select @string= case when @iterator <(select max(rowid) from @final) then 
@string+' select '+@string2+ ' union all '  else @string+' select '+@string2 end 
set @iterator=@iterator+1

end 

exec(''+@string+'')