使用两个聚合列进行透视

时间:2018-03-23 11:37:19

标签: sql sql-server pivot

我正在尝试透视表,但我有多个聚合列。

数据看起来像

enter image description here

返回看起来像

enter image description here

抱歉,我无法弄清楚如何获取这些表格,所以我已经拍摄了片段。

我正在使用透视代码:

select *

    from(   
            select 
                col1, 
                per1,
                per2

            from    
                table a
                left join table 2 b on a.ID = b.ID 

            where 
                a.END_DTTM is null

            group by 
                a.COL3                      

            ) d

            pivot 
            (
                max(d.per1),
                max(d.per2)
                for d.col1 in (A, B, C)
                ) piv;

2 个答案:

答案 0 :(得分:2)

您无法在同一步骤中进行两次转轴,因为执行转轴会执行非引用列的隐式GROUP BY。除了聚合函数和透视列之外,您必须仅对除了具有不同值的列的子集应用透视。请尝试以下方法:

;WITH PrePivot1 AS
(
    SELECT
        T.col1,
        T.per1
    FROM
        YourTable AS T
),
PrePivot2 AS
(
    SELECT
        T.col1,
        T.per2
    FROM
        YourTable AS T
),
Pivot1 AS
(
    SELECT
        P.A,
        P.B,
        P.C
    FROM
        PrePivot1 AS R
        PIVOT (
            MAX(R.per1) FOR R.Col1 IN ([A], [B], [C])
        ) AS P
),
Pivot2 AS
(
    SELECT
        P.A,
        P.B,
        P.C
    FROM
        PrePivot2 AS R
        PIVOT (
            MAX(R.per2) FOR R.Col1 IN ([A], [B], [C])
        ) AS P
)
SELECT
    Concept = 'Per1',
    P1.A,
    P1.B,
    P1.C,
FROM
    Pivot1 AS P1
UNION ALL
SELECT
    Concept = 'Per2',
    P2.A,
    P2.B,
    P2.C,
FROM
    Pivot2 AS P2

编辑:

要进行进一步的计算,您可以继续链接CTE。变化

SELECT
    Concept = 'Per1',
    P1.A,
    P1.B,
    P1.C,
FROM
    Pivot1 AS P1
UNION ALL
SELECT
    Concept = 'Per2',
    P2.A,
    P2.B,
    P2.C,
FROM
    Pivot2 AS P2

,
UnionResults AS
(
    SELECT
        Concept = 'Per1',
        P1.A,
        P1.B,
        P1.C,
    FROM
        Pivot1 AS P1
    UNION ALL
    SELECT
        Concept = 'Per2',
        P2.A,
        P2.B,
        P2.C,
    FROM
        Pivot2 AS P2
)
SELECT
    U.Concept,
    U.A,
    U.B.
    U.C,
    ADivision = CASE
        WHEN U.C <> 0
        THEN U.A / U.C END
FROM
    UnionResults AS U

答案 1 :(得分:2)

您还可以使用apply(即cross apply)运算符将数据转换为列中的行

select 
      name as pear,
      max(case when cols = 'A' then value end) [A],
      max(case when cols = 'B' then value end) [B],
      max(case when cols = 'C' then value end) [C]
from table t
cross apply (values (col1, 'per1', per1), (col1, 'per2', per2))a(cols, name, value)
group by name