TSQL Pivot 4值列

时间:2018-05-29 14:20:14

标签: sql sql-server sql-server-2008 tsql pivot

在SQL Server 2008中,我试图使用Period列将下面的表格格式“旋转”为宽格式(在实际数据中有5个不同的句点)。

我已经搜索过但尚未找到解决方法。我已经提到https://www.tangrainc.com/blog/2009/01/pivoting-on-multiple-columns/#comment-504但是无法将逻辑转换为> 2值列 - 我需要它。

有什么想法?您可能已经猜到我不是SQL专家。使用SQL Server 2008。

谢谢, 克里斯

PS。第一个S / O帖子!

试图从平台上取下来:

enter image description here

到一张宽桌子:

enter image description here

1 个答案:

答案 0 :(得分:5)

您可以使用条件聚合:

select Cat, Dept,
       sum(case when Period = 'LW' then New else 0 end) as [Net LW],
       sum(case when Period = 'LY' then New else 0 end) as [Net LY],
       sum(case when Period = 'LW' then Gross else 0 end) as [Gross LW],
       sum(case when Period = 'LY' then Gross else 0 end) as [Gross LY],
       sum(case when Period = 'LW' then Profit else 0 end) as [Profit LW],
       sum(case when Period = 'LY' then Profit else 0 end) as [Profit LY],
       sum(case when Period = 'LW' then Units else 0 end) as [Units LW],
       sum(case when Period = 'LY' then Units else 0 end) as [Units LY]
from table t
group by Cat, Dept;