读书人

SQL列行变换

发布时间: 2012-09-05 15:19:35 作者: rapoo

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) 

读书人网 >SQL Server

热点推荐