tsql排序方式与XML路径不同

时间:2020-10-28 11:42:44

标签: tsql stored-procedures pivot sql-order-by distinct

我有一个查询,稍后将使用它来进行动态数据透视。我想在进行区分之前对这个查询进行排序。我怎样才能做到这一点?每当我下令订购时,它都会完全打破常规。

    DECLARE @cols NVARCHAR(max);
SET @cols = STUFF
(
    (SELECT distinct ',' + c.[PivotColumnTitle]
        FROM [myTable] c
        WHERE c.Id = @idInput
        AND c.IsPivotVisible = 1
              --order by c.PivotColumnOrder
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)') 
    ,1,1,''
)

1 个答案:

答案 0 :(得分:1)

尝试一下:

DECLARE @cols NVARCHAR(max);

SET @cols = STUFF
(
    (
        SELECT ',' + c.[PivotColumnTitle]
        FROM [myTable] c
        WHERE c.Id = @idInput
            AND c.IsPivotVisible = 1
        GROUP BY c.[PivotColumnTitle]
        order by MAX(c.PivotColumnOrder)
        FOR XML PATH(''), TYPE
    ).value('.', 'NVARCHAR(MAX)') 
    ,1,1,''
)