SQL Max多列的日期,返回列名

时间:2017-12-29 18:43:03

标签: sql-server-2008 max

使用MS SQL Server 2008,我正在进行查询以计算每行的10列的最大日期。该查询如下。我还需要列出具有最大日期的列的名称。所以Query会给我[Last Step Date]和[Last Step Name]。我如何获得[最后一步名称]?

SELECT (SELECT MAX(LastUpdateDate)
        FROM   (VALUES ([Step 1]),
                       ([Step 2]),
                       ([Step 3]),
                       ([Step 4]),
                       ([Step 5]),
                       ([Step 6]),
                       ([Step 7]),
                       ([Step 8]),
                       ([Step 9]),
                       ([Step 10]) ) AS UpdateDate(LastUpdateDate)) AS [Last Step Date]
FROM   MyTable 

1 个答案:

答案 0 :(得分:1)

您可以使用

SELECT ca.ColName, ca.LastUpdateDate
FROM   YourTable
       CROSS APPLY (SELECT TOP 1 *
                    FROM (VALUES
                       ('Step1', [Step 1]),
                       ('Step2', [Step 2]),
                       ('Step3', [Step 3]),
                       ('Step4', [Step 4]),
                       ('Step5', [Step 5]),
                       ('Step6', [Step 6]),
                       ('Step7', [Step 7]),
                       ('Step8', [Step 8]),
                       ('Step9', [Step 9]),
                       ('Step10', [Step 10]) ) UpdateDate(ColName, LastUpdateDate)
                    ORDER  BY LastUpdateDate DESC)ca 

SQL Fiddle