前端时间写了一个按月统计的报表,首先用了最笨的办法,一个个单元格值计算,后来试了一下sqlserver自带的两个函数,比原来要简单一些,分享一下语句如下:
select * from (
select sname,smonth+colname as colname,colvalue from
(
select 'a' as sname,'jan' as smonth,123 as iqu,234 as imoney
union
select 'b' as sname,'jan' as smonth,234 as iqu,543 as imoney
union
select 'c' as sname,'feb' as smonth,645 as iqu,754 as imoney
union
select 'c' as sname,'may' as smonth,645 as iqu,754 as imoney
) as m
unpivot -----列转行
(
colvalue for colname in(iqu,imoney)
) as n
) as x
pivot-------行转列
(
max(colvalue) for colname in([janiqu],[janimoney],[febiqu],[febimoney],[mayiqu],[mayimoney])
) as y
本文介绍了如何使用SQLserver的UNPIVOT和PIVOT函数来简化按月统计数据报表的编写过程。通过示例代码,展示了从原始数据到最终的行列转换,大大减少了计算的复杂性,提高了查询效率。
62

被折叠的 条评论
为什么被折叠?



