如何在动态数据透视表中按行然后按列排序

时间:2019-04-23 20:20:59

标签: sql-server pivot dynamic-pivot

我用我想要的所有数据创建了一个临时表。然后,我使用动态数据透视表提取数据,并试图弄清楚如何按行排序,然后按数据透视表列排序。我可以对行进行排序,但无法弄清楚如何对透视列进行排序。

SET @COLS = N'';
SET @COLS2 = N'';

SELECT @COLS += N', ISNULL(' + QUOTENAME(PivotedName) + ',0) AS ' + QUOTENAME(PivotedName), @COLS2 += N', ' + QUOTENAME(PivotedName)
FROM    (SELECT DISTINCT(PivotedName) FROM #TEMP1 T1) AS X;

SET @SQL = N'
SELECT [ID#],[Name],' + STUFF( @COLS, 1, 2, '') + '
FROM        
(
    SELECT T1.[ID#], T1.[Name], T1.PivotedName, T1.PivotedAggregate FROM #TEMP1 T1 

) AS C
PIVOT 
(
    MAX(PivotedAggregate) FOR PivotedName IN (' + STUFF(REPLACE(@COLS2, ', [', ',['), 1, 1, '') + ')
) AS P

ORDER BY [ID#] DESC
;';


EXECUTE SP_EXECUTESQL @SQL;

返回的结果是这样的,它们按照ID#DESC排序。但其次,我希望它们按“ PivotName”而不是按字母顺序排序,实际上是按另一列“ SortOrder”排序,该列在#TEMP1中可用。

实际结果:

ID# Name    PivotName1  PivotName4  PivotName3  PivotName2
10  Jon     10          0.91            9           0.91
9   Jane    8           15.8            14          0.8
8   Tom     6           0.84            6           0.84
7   Steve   3.37        0.85            37.5        0.99
6   Bob     0.75        0.73            0.75        0.73

所需结果:

ID# Name    PivotName1  PivotName2  PivotName3  PivotName4
10  Jon     10          0.91        9           0.91
9   Jane    8           0.8         14          15.8

2 个答案:

答案 0 :(得分:0)

正如我所说,您需要添加一个ORDER BY。只需更改:

SELECT @COLS += N', ISNULL(' + QUOTENAME(PivotedName) + ',0) AS ' + QUOTENAME(PivotedName), @COLS2 += N', ' + QUOTENAME(PivotedName)
FROM    (SELECT DISTINCT(PivotedName) FROM #TEMP1 T1) AS X;

收件人

SELECT @COLS += N', ISNULL(' + QUOTENAME(PivotedName) + ',0) AS ' + QUOTENAME(PivotedName), @COLS2 += N', ' + QUOTENAME(PivotedName)
FROM    (SELECT DISTINCT(PivotedName) FROM #TEMP1 T1) AS X ORDER BY PivotedName;

答案 1 :(得分:0)

SELECT @COLS += N', ISNULL(' + QUOTENAME(PivotedName) + ',0) AS ' + QUOTENAME(PivotedName), @COLS2 += N', ' + QUOTENAME(PivotedName)
FROM    (SELECT DISTINCT(PivotedName), SortOrder FROM #TEMP1 T1) AS X ORDER BY SortOrder;

知道了。我从临时表中拉出排序顺序进行排序,但未在最终的sql中使用它。感谢您的讨论。