返回基于其保存记录中最大值的列名

时间:2017-07-12 07:27:35

标签: sql-server unpivot

我有一张具有以下结构的表......

+--------+------+------+------+------+------+
| ID     | colA | colB | colC | colD | colE | [...] etc.
+--------+------+------+------+------+------+
| 100100 | 15   | 100  | 90   | 80   | 10   | 
+--------+------+------+------+------+------+
| 100200 | 10   | 80   | 90   | 100  | 10   | 
+--------+------+------+------+------+------+
| 100300 | 100  | 90   | 10   | 10   | 80   | 
+--------+------+------+------+------+------+

我需要返回列名的连接值,每行最多包含3个值...

+--------+----------------------------------+
| ID     | maxCols                          |
+--------+----------------------------------+
| 100100 | colB,colC,colD                   |
+--------+------+------+------+------+------+
| 100200 | colD,colC,colB                   | 
+--------+------+------+------+------+------+
| 100300 | colA,colB,colE                   | 
+--------+------+------+------+------+------+
  • 没有连接列名称是可以的,如果更简单,可以maxCol1 | maxCol2 | maxCol3
  • 连接时列的顺序很重要
  • 列数有限且不动态
  • 行数很多

2 个答案:

答案 0 :(得分:2)

您可以使用UNPIVOT并为每个ID获得TOP 3

;with temp AS
(
    SELECT ID, ColValue, ColName
    FROM @SampleData sd
    UNPIVOT
    (
       ColValue For ColName in ([colA], [colB], [colC], [colD], [colE])
    ) unp
)
SELECT sd.ID, ca.ColMax
FROM @SampleData sd
CROSS APPLY
(
    SELECT STUFF(
              (
                SELECT TOP 3 WITH TIES
                       ',' + t.ColName
                FROM temp t
                WHERE t.ID = sd.ID
                ORDER BY t.ColValue DESC
                FOR XML PATH('')
              )
             ,1,1,'') AS ColMax
) ca

在此处查看演示:http://rextester.com/CZCPU51785

答案 1 :(得分:1)

以下是使用Cross ApplyTable Valued Constructor

执行此操作的一个技巧
SELECT Id,
       maxCols= Stuff(cs.maxCols, 1, 1, '')
FROM   Yourtable
       CROSS apply(SELECT(SELECT TOP 3 ',' + NAME
                          FROM   (VALUES (colA,'colA'),(colB,'colB'),(colC,'colC'),
                                         (colD,'colD'),(colE,'colE')) tc (val, NAME)
                          ORDER  BY val DESC
                          FOR xml path, type).value('.[1]', 'nvarchar(max)')) cs (maxCols) 

如果需要,可以使用Information_schema.Columns

使其动态化