SQL中竖表变横表及统计功能实现的问题

在SQL中如何能使根据左表中的数据,自动生成右边中的数据呢

在源表加一列月份,输入月份值。


然后对源数据使用“数据透视表”



-_-|||,没注意,你是说SQL


select
[部门],
[费用项目],
sum(case when substring([日期],5,2) = '01' then [金额] else 0 end) as [1月总],
sum(case when substring([日期],5,2) = '02' then [金额] else 0 end) as [2月总],
sum(case when substring([日期],5,2) = '03' then [金额] else 0 end) as [3月总],
sum(case when substring([日期],5,2) = '04' then [金额] else 0 end) as [4月总],
sum(case when substring([日期],5,2) = '05' then [金额] else 0 end) as [5月总],
sum(case when substring([日期],5,2) = '06' then [金额] else 0 end) as [6月总],
sum(case when substring([日期],5,2) = '07' then [金额] else 0 end) as [7月总],
sum(case when substring([日期],5,2) = '08' then [金额] else 0 end) as [8月总],
sum(case when substring([日期],5,2) = '09' then [金额] else 0 end) as [9月总],
sum(case when substring([日期],5,2) = '10' then [金额] else 0 end) as [10月总],
sum(case when substring([日期],5,2) = '11' then [金额] else 0 end) as [11月总],
sum(case when substring([日期],5,2) = '12' then [金额] else 0 end) as [12月总]
from tableA
group by [部门],[费用项目]

温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-09-23
可以使用 case when ,也可以使用 pivot。
相似回答