gpt4 book ai didi

sql - 如何按升序排列 SQL 数据透视表的列

转载 作者:行者123 更新时间:2023-12-02 18:20:20 26 4
gpt4 key购买 nike

有人可以帮我按升序排列列吗?

我的数据透视表的输出如下:

Ref             role_name   offer_id    10000   104000  8000    8400
43132_43282 Call Center 1 1 0 0 6
43132_43282 Others 1 2 0 0 3

相反,我希望它是这样的:

Ref             role_name   offer_id    8000    8400    10000   104000
43132_43282 Call Center 1 0 6 1 0
43132_43282 Others 1 0 3 2 0


DECLARE @cols AS NVARCHAR(MAX), -- for pivot
@cols2 AS NVARCHAR(MAX), -- for select
@query AS NVARCHAR(MAX);

SET @cols = STUFF((
SELECT DISTINCT ',' + QUOTENAME(c.[Offer_cover])
FROM #cover2 c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
-- this is for the SELECT
SET @cols2 = STUFF((
SELECT DISTINCT ',' + 'ISNULL(' + QUOTENAME(c.[Offer_cover]) + ', 0) ' + QUOTENAME(c.[Offer_cover])
FROM #cover2 c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 1, '')
SET @query = 'SELECT Ref,role_name,offer_id, ' + @cols2 + ' from
(
select *
from #cover2
) x
pivot
(
SUM(cover_earning_Count)
for [Offer_cover] in (' + @cols + ')
) p'

EXECUTE (@query)

最佳答案

您能否在 @cols2 变量选择中添加 GROUP BY, ORDER BY [Offer_cover] 并删除 DISTINCT

所以查询将是:

SET @cols2 = STUFF((
SELECT ',' + 'ISNULL(' + QUOTENAME(c.[Offer_cover]) + ', 0) ' + QUOTENAME(c.[Offer_cover])
FROM #cover2 c
GROUP BY c.[Offer_cover] -- changes here
ORDER BY c.[Offer_cover] -- changes here
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)'), 1, 1, '')

它会按升序返回@cols2,因此会影响最终结果。

关于sql - 如何按升序排列 SQL 数据透视表的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51279837/

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