我有下面的sql数据结构,需要将它从每月每行转换为每行一列。
我知道pivot只能用一个列来完成,但是想不出一个合适的方法来使用case语句来翻转表。
我想从这个改变:

要这样做:

用于创建该结构的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我相信这不是最好的方法,欢迎您的建议。
一如既往地提前感谢
发布于 2017-07-17 19:16:17
它需要同时使用unpivot和pivot。试试这个方法
SELECT *
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 Live Demo
https://stackoverflow.com/questions/45142653
复制相似问题