首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >案例表pivot / pivot多列- MSSQL 2008

案例表pivot / pivot多列- MSSQL 2008
EN

Stack Overflow用户
提问于 2017-07-17 19:07:40
回答 1查看 238关注 0票数 1

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

我知道pivot只能用一个列来完成,但是想不出一个合适的方法来使用case语句来翻转表。

我想从这个改变:

要这样做:

用于创建该结构的SQL为:

代码语言:javascript
复制
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语句:

代码语言:javascript
复制
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

我相信这不是最好的方法,欢迎您的建议。

一如既往地提前感谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-07-17 19:16:17

它需要同时使用unpivotpivot。试试这个方法

代码语言:javascript
复制
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

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45142653

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档