gpt4 book ai didi

sql-server - 根据两列动态旋转

转载 作者:行者123 更新时间:2023-12-01 13:13:00 24 4
gpt4 key购买 nike

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

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

我想得到如下结果:
  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)

当我尝试再次更改 errorcounts的问题时,出现以下错误:

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

最佳答案

首先用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

关于sql-server - 根据两列动态旋转,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58875717/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com