0

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

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”而不是按字母顺序排序,实际上是按#TEMP1 中可用的另一列“SortOrder”。

实际结果:

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
4

2 回答 2

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 中使用它。感谢您的讨论。

于 2019-04-25T16:42:10.733 回答
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;
于 2019-04-24T07:55:38.577 回答