【问题标题】:case table pivot / pivot multiple column - MSSQL 2008案例表透视/透视多列 - MSSQL 2008
【发布时间】:2017-07-17 11:07:39
【问题描述】:

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

我知道枢轴只能用一个列完成,但我想不出一种体面的方式来使用 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

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

一如既往地提前感谢

【问题讨论】:

    标签: sql-server pivot case multiple-columns


    【解决方案1】:

    它需要unpivotpivot 的组合。试试这个方法

    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

    【讨论】:

    • 交叉申请,我喜欢。
    猜你喜欢
    • 2016-05-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-05
    相关资源
    最近更新 更多