如何才能使这个SQL查询更简单/更短?

时间:2011-10-17 10:57:00

标签: sql sql-server join left-join greatest-n-per-group

它应该从ProcessHable表中的最新记录的SystemTable和LoadStatus列返回一些字段。关系是1对多:

SELECT ST.[SystemDetailID], ST.[SystemName], LH.LatestLoadStatus
FROM [SystemTable] AS ST
LEFT OUTER JOIN 
    (
     SELECT LHInner.LoadStatus AS LatestLoadStatus, LHInner.SystemDetailID FROM [dbo].[LoadHistory] AS LHInner
        WHERE LHInner.LoadHistoryID in 
        (
            SELECT LatestLoadHisotoryID FROM 
            (
                SELECT MAX(LoadHistoryID) as LatestLoadHisotoryID, SystemDetailID FROM [dbo].[LoadHistory]
                GROUP BY SystemDetailID
            ) l
        )   
    ) AS LH ON ST.SystemDetailID = LH.SystemDetailID

谢谢,

2 个答案:

答案 0 :(得分:2)

这是每组最大的查询。

一种方法

SELECT ST.[SystemDetailID],
       ST.[SystemName],
       LH.LatestLoadStatus
FROM   [SystemTable] AS ST
       OUTER APPLY (SELECT TOP 1 *
                    FROM   [dbo].[LoadHistory] LH
                    WHERE  ST.SystemDetailID = LH.SystemDetailID
                    ORDER  BY LoadHistoryID DESC) LH  

您也可以使用row_number

WITH LH
     AS (SELECT *,
                ROW_NUMBER() OVER (PARTITION BY SystemDetailID 
                                       ORDER BY LoadHistoryID DESC) RN
         FROM   [dbo].[LoadHistory])
SELECT ST.[SystemDetailID],
       ST.[SystemName],
       LH.LatestLoadStatus
FROM   [SystemTable] AS ST
       LEFT JOIN LH
         ON LH.SystemDetailID = ST.SystemDetailID
            AND LH.RN = 1  

答案 1 :(得分:0)

SELECT ST.[SystemDetailID], ST.[SystemName], LH.LatestLoadStatus
FROM [SystemTable] AS ST
INNER JOIN [dbo].[LoadHistory] AS LH 
ON ST.SystemDetailID = LH.SystemDetailID
AND LH.LoadHistoryID IN 
                     (SELECT MAX(LoadHistoryID) as LoadHistoryID 
                      FROM [dbo].[LoadHistory]
                      GROUP BY SystemDetailID )