如何在SQL中一起使用数据透视和分组依据?

时间:2018-11-23 07:21:41

标签: sql-server tsql sql-server-2008 sql-server-2012

我想获得以列形式显示在行中的结果。我是SQL的新手,想知道如何在以下情况下应用数据透视

代码:

SELECT T.NAME, T.CODE, RN FROM(
SELECT NAME, CODE, SUM(PROFIT), ROW_NUMBER() 
OVER (PARTITION BY NAME ORDER BY NAME, SUM(PROFIT) DESC, CODE)RN 
FROM TABLE1
GROUP BY NAME, CODE)T WHERE RN <= 3

我的当前结果:

NAME CODE RN
A    XX   1
A    YY   2
A    ZZ   3
B    XX   1
B    PP   2
C    GH   1
C    JU   2
C    GQ   3

预期结果:

NAME 1  2  3
A    XX YY ZZ
B    XX PP NULL
C    GH JU GQ

1 个答案:

答案 0 :(得分:2)

这是一种方式。 只需PIVOT(),如下所示。将当前查询封装为CTE或派生表

SELECT *
FROM
(
    SELECT T.NAME, T.CODE, RN 
    FROM
    (
        SELECT NAME, CODE, SUM(PROFIT), 
               ROW_NUMBER() OVER (PARTITION BY NAME ORDER BY NAME, SUM(PROFIT) DESC, CODE)RN 
        FROM TABLE1
        GROUP BY NAME, CODE
    )T 
    WHERE RN <= 3
) D
PIVOT
(
    MAX(CODE)
    FOR RN IN ([1] , [2], [3])
) P