日期:2014-05-18  浏览次数:20456 次

SQL查询列设置
表结构
A B C D
w f ff 100
2 df df 200
ff ff ff 300
查询出来的结果:
ff df
400 200
也就说把C列横着排列,并把C列中相同的列求D的和

------解决方案--------------------
SQL code
--> 测试数据: #A
if object_id('tempdb.dbo.#A') is not null drop table #A
create table #A (A varchar(11),B varchar(11),C varchar(11),D int)
insert into #A
select 'w','f','ff',100 union all
select '2','df','df',200 union all
select 'ff','ff','ff',300

select * from
    (select C,D from #A) a
pivot
    (sum(D) for C in (ff,df)) b
/*
ff          df
----------- -----------
400         200
*/

------解决方案--------------------
SQL code


create table #A (A varchar(11),B varchar(11),C varchar(11),D int)
insert into #A
select 'w','f','ff',100 union all
select '2','df','df',200 union all
select 'ff','ff','ff',300

select 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
) T

drop table #A

------解决方案--------------------
探讨
楼上的,表的属性C不一定只有这2个啊,要是有100个不同的属性C,那你这语句岂不是很长.