SQL查询列设置
表结构
A B C D
w f ff 100
2 df df 200
ff ff ff 300
查询出来的结果:
ff df
400 200
也就说把C列横着排列,并把C列中相同的列求D的和
[解决办法]
--> 测试数据: #Aif object_id('tempdb.dbo.#A') is not null drop table #Acreate table #A (A varchar(11),B varchar(11),C varchar(11),D int)insert into #Aselect 'w','f','ff',100 union allselect '2','df','df',200 union allselect 'ff','ff','ff',300select * from (select C,D from #A) apivot (sum(D) for C in (ff,df)) b/*ff df----------- -----------400 200*/
[解决办法]
create table #A (A varchar(11),B varchar(11),C varchar(11),D int)insert into #Aselect 'w','f','ff',100 union allselect '2','df','df',200 union allselect 'ff','ff','ff',300select df=max(case when c='df' then d end),ff=max(case when c='ff' then d end) from ( select C,sum(D) D from #A group by C) Tdrop table #A
[解决办法]