这个列转行该如何实现?
表
Create table ttt(ID int not null,SID int ,A varchar(10))INsert into tttSelect 1,1,'aa'UnionSelect 1,2,'bb'unionSelect 1,3,'cc'UnionSelect 2,1,'a'UnionSelect 2,2,'B'Select ID,Case when sid=1 then A else Null End as sid1,Case When Sid=2 then A else Null End as sid2,Case When Sid=3 then A Else Null End as Sid3 From ttt group by id,A,Sid
ID,Sid1,Sid2,Sid31, aa, bb, cc2, a, B---进行到上面一步查询不会了
Select ID,max(Case when SID=1 then A else Null End) SID1 ,max(Case when SID=2 then A else Null End) SID2 ,max(Case when SID=3 then A else Null End) SID3From ttt group by ID
[解决办法]
Create table ttt(ID int not null,[SID] int ,A varchar(10))INsert into tttSelect 1,1,'aa'UnionSelect 1,2,'bb'unionSelect 1,3,'cc'UnionSelect 2,1,'a'UnionSelect 2,2,'B'--[SID]字段值较多时推荐使用动态转换declare @str varchar(1000)set @str=''select @str=@str+',['+ltrim([SID])+']=max(case when [SID]=' +LTRIM([SID])+' then A else '''' end)'from tttgroup by [SID]exec('select ID'+@str+' from ttt group by ID')/*ID 1 2 3-----------------1 aa bb cc2 a B */
[解决办法]
Create table ttt(ID int not null,[SID] int ,A varchar(10))INsert into tttSelect 1,1,'aa'UnionSelect 1,2,'bb'unionSelect 1,3,'cc'UnionSelect 2,1,'a'UnionSelect 2,2,'B'--[SID]字段值较多时推荐使用动态转换declare @str varchar(1000)set @str=''select @str=@str+',[SID'+ltrim([SID])+']=max(case when [SID]=' +LTRIM([SID])+' then A else '''' end)'from tttgroup by [SID]exec('select ID'+@str+' from ttt group by ID')/*ID SID1 SID2 SID3------------------------------1 aa bb cc2 a B */
[解决办法]
Create table ttt(ID int not null,SID int ,A varchar(10))INsert into tttSelect 1,1,'aa'UnionSelect 1,2,'bb'unionSelect 1,3,'cc'UnionSelect 2,1,'a'UnionSelect 2,2,'B'select ID, isnull([1],'') Sid1, isnull([2],'') Sid2, isnull([3],'') Sid3from ttt apivot(max(A) for SID in([1],[2],[3])) p/*ID Sid1 Sid2 Sid3----------- ---------- ---------- ----------1 aa bb cc2 a B (2 row(s) affected)*/