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

问题描述 投票:1回答:1

使用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 
sql-server-2008 max
1个回答
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

© www.soinside.com 2019 - 2024. All rights reserved.