简体   繁体   中英

TSQL Pivot 4 value columns

In SQL Server 2008 I'm trying to 'pivot' the table format below to wide format using the Period column (in the real data there are 5 different Periods).

I've searched but not yet found a solution to this. I've referred to https://www.tangrainc.com/blog/2009/01/pivoting-on-multiple-columns/#comment-504 but cannot translate the logic to >2 value columns - which I need.

Any thoughts? You may have guessed I'm no SQL expert. Using SQL Server 2008.

Thanks, Chris

ps. first S/O post!

Trying to get from a flat table:

在此输入图像描述

to a wide table:

在此输入图像描述

You can use conditional aggregation:

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; 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM