日期:2014-05-17  浏览次数:20544 次

SQL列行转换
视图一(动态):
select chuliren as 处理人,
SUM(case when month(PetitionTime)='8' then isnull(consuming,0) else 0 end) as 八月,
SUM(case when month(PetitionTime)='9' then isnull(consuming,0) else 0 end) as 九

from dbo.Table1  
where chuliren is not null 
group by chuliren
 
视图一(结果):
  处理人 八月 九月
1 A君 60 0
2 B君 1270 0
3 C君 0 0
 
要把视图一列行转换成(需求):
  A君 B君 C君
8月 60 1270 0
9月 0 0 0

------解决方案--------------------
SQL code
select month(PetitionTime)
sum(case when chuliren ='A君' then isnull(consuming,0) else 0 end) as A君,
sum(case when chuliren ='B君' then isnull(consuming,0) else 0 end) as B君,
sum(case when chuliren ='C君' then isnull(consuming,0) else 0 end) as C君
from dbo.Table1   
where chuliren is not null  
group by month(PetitionTime)