排序动态数据透视表的行

时间:2014-06-18 19:59:12

标签: sql sql-server dynamic-sql

我有以下查询来动态调整某些行信息:

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

    select @cols = STUFF((SELECT ',' + QUOTENAME(convert(char(50), ScheduleEndTime, 120))
                   FROM metersNotRead
                   group by ScheduleEndTime
                   order by ScheduleEndTime DESC
                   FOR XML PATH(''), TYPE
                   ).value('.', 'NVARCHAR(MAX)') 
                   ,1,1,'')

    set @query = 'SELECT ScheduleName, MeterID, CurrentGK,
                ' + @cols + ' from 
                 (
                    select ScheduleName, MeterID, CurrentGK, ScheduleEndTime, ''Y'' flag
                    from metersNotRead
                ) x
                pivot 
                (
                    max(flag)
                    for ScheduleEndTime in (' + @cols + ')
                ) p 
                order by ' + @cols +' DESC
        '

    execute(@query)

它给了我正确的结果,但我想知道如何按第一个动态列排序行,然后是第二个,依此类推,直到所有动态列都按顺序排序。

我现在的结果是这样的:

ScheduleName   MeterID   CurrentGK    FirstDynamicCol    SecondDynamicCol    ETC
textName1      exampleID1  --         NULL               Y                   
taxtName2      exampleID2  --         Y                  NULL                

我希望他们是这样的:

ScheduleName   MeterID   CurrentGK    FirstDynamicCol    SecondDynamicCol    ETC
textName2      exampleID2  --         Y                  NULL                   
taxtName1      exampleID1  --         NULL               Y                

1 个答案:

答案 0 :(得分:1)

试试这个,将你的第一个列名放在它自己的变量中,然后按此排序。

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

select @orderby = STUFF((SELECT ',' + QUOTENAME(convert(char(50), ScheduleEndTime, 120)) + ' desc'
               FROM metersNotRead
               group by ScheduleEndTime
               order by ScheduleEndTime DESC
               FOR XML PATH(''), TYPE
               ).value('.', 'NVARCHAR(MAX)') 
               ,1,1,'')

select @cols = STUFF((SELECT ',' + QUOTENAME(convert(char(50), ScheduleEndTime, 120))
               FROM metersNotRead
               group by ScheduleEndTime
               order by ScheduleEndTime DESC
               FOR XML PATH(''), TYPE
               ).value('.', 'NVARCHAR(MAX)') 
               ,1,1,'')

set @query = 'SELECT ScheduleName, MeterID, CurrentGK,
            ' + @cols + ' from 
             (
                select ScheduleName, MeterID, CurrentGK, ScheduleEndTime, ''Y'' flag
                from metersNotRead
            ) x
            pivot 
            (
                max(flag)
                for ScheduleEndTime in (' + @cols + ')
            ) p 
            order by ' + @orderby


execute(@query)