根据两列动态旋转

时间:2019-11-15 11:06:10

标签: sql-server tsql pivot dynamic-pivot

我有下表记录了用户在聊天室所花费的时间:

user_id | duration         | errorscounts   | week
--------+------------------+----------------+--------
   1    |      0           |     99         |  1
   2    |    234           |      5         |  1
   1    |   4150           |      9         |  2
   2    |    142           |     16         |  2
   3    |    236           |     40         |  2  
   1    |    649           |     17         |  3
   3    |    500           |     78         |  3

I want to get the result as below : 
user_id | week1ofduration |  week1errorscounts | .... | week(n)ofduration |  week(n)errorscounts

我已经尝试过:

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT distinct ',' + QUOTENAME(t.week) 
            FROM MyTable t
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

        set @query = 'SELECT user_id, ' + @cols + ' from 
            (
                select user_id
                    , duration
                    , errorscounts
                from MyTable
           ) x
            pivot 
            (
                 max(duration)
                for week in (' + @cols + ')
            ) p '


execute(@query)

当我尝试再次更改错误计数的时间时,出现以下错误:

  

PIVOT运算符中指定的列名“ 1”与   PIVOT参数中现有的列名称。

1 个答案:

答案 0 :(得分:3)

首先UNPIVOT数据,然后PIVOT。可玩的部分是准备最终标题。

DROP TABLE IF EXISTS #MyTable;

CREATE TABLE #MyTable 
(
    [user_id] INT
   ,[duration] INT
   ,[errorscounts] INT
   ,[week] INT
);

INSERT INTO #MyTable ([user_id], [duration], [errorscounts], [week])
VALUES (1, 0, 99, 1)
      ,(2, 234, 5, 1)
      ,(1, 4150, 9, 2)
      ,(2, 142, 16, 2)
      ,(3, 236, 40, 2)
      ,(1, 649, 17, 3)
      ,(3, 500, 78, 3);

DECLARE @cols AS NVARCHAR(MAX)
       ,@cols_week_headings AS NVARCHAR(MAX)
       ,@cols_duration_headings AS NVARCHAR(MAX)
       ,@query AS NVARCHAR(MAX);


SET @cols = STUFF
(
    (
        SELECT [row_value]
        FROM
        (
            SELECT DISTINCT [week] + 0.1
                           ,',' + QUOTENAME('week' + CAST([week] AS VARCHAR(12)) + 'duration')
            FROM #MyTable
            UNION ALL
            SELECT DISTINCT [week] + 0.2
                           ,',' + QUOTENAME('week' + CAST([week] AS VARCHAR(12)) + 'errorscounts')
            FROM #MyTable
        ) DS ([row_id], [row_value])
        ORDER BY [row_id] + 0.1
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)') 
    ,1
    ,1
    ,''
);


SET @query = N'

SELECT *
FROM
(
    SELECT [user_id]
            ,''week'' + CAST([week] AS VARCHAR(12)) + [column] AS [column]
            ,[value]
    FROM #MyTable
    UNPIVOT
    (
        [value] FOR [column] IN ([duration], [errorscounts])
    ) UNPVT
) DS
PIVOT
(
    MAX([value]) FOR [column] IN (' + @cols + ')
) PVT'


execute(@query)

enter image description here