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

时间:2018-07-11 07:42:35

标签: sql sql-server

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

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

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)

1 个答案:

答案 0 :(得分:3)

您可以在GROUP BY, ORDER BY [Offer_cover]变量选择中添加@cols2并删除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,因此会影响最终结果。