案例表pivot / pivot多列 - MSSQL 2008

时间:2017-07-17 11:07:40

标签: sql-server pivot case multiple-columns

我有以下的sql数据结构,需要将其从每行一个月转换为每行一列。

我知道枢轴只能用一个columbn完成,但是不能想到使用case语句来翻转表格的正确方法。

我想改变这个:

structure is currently this

到此: desired structure

创建结构的SQL是:

create table records (month int,apples int, grapes int, oranges int);

insert into records values (1,1,43,12)
insert into records values (2,23,43,5)
insert into records values (3,32,43,12)
insert into records values (4,23,43,12)
insert into records values (5,23,434,12)
insert into records values (6,23,43,12)
insert into records values (7,33,43,12)
insert into records values (8,23,55,12)
insert into records values (9,23,4332,12)
insert into records values (10,223,43,18)
insert into records values (11,223,43,12)
insert into records values (12,23,143,122)

我不确定如何在一个语句中执行此操作或为服务器创建额外开销?

可以使用case语句正确但需要join语句:

select type,sum(jan)jan,sum(feb)feb,sum(mar) mar from ( select 
'apples' type,case when month=1 then apples else 0 end jan
,case when month=2 then apples else 0 end feb
,case when month=3 then apples else 0 end mar
 from #records ) t group by type
 UNION
 select type,sum(jan)jan,sum(feb)feb,sum(mar) mar from ( select 
'oranges' type,case when month=1 then oranges else 0 end jan
,case when month=2 then oranges else 0 end feb
,case when month=3 then oranges else 0 end mar
 from #records ) t group by type

我确信这不是他的最佳方法,建议欢迎。

一如既往地感谢

1 个答案:

答案 0 :(得分:1)

它需要pivotSELECT * FROM (SELECT month, names, value FROM Yourtable CROSS apply (VALUES ('apples',apples),('grapes',grapes),('oranges',oranges)) tc (names, value)) a PIVOT (Max(value) FOR month IN ([1],[2],[3],[4],[5],[6],[7],[8],[9],[10],[11],[12])) pv 的组合。试试这个方法

{{1}}

Live Demo