加入最大日期/最大记录

时间:2013-11-27 19:11:31

标签: sql join max

我想出了一种方法,但它的速度非常慢,并且有太多的子查询,因为它可能会有成千上万的记录,所以它会像它一样运行。基本上,我需要每个PendingId的最大日期最多3次。通常它可能只有1个pendingId,导致2和3为空。这就是我现在所说的超慢:

SELECT  a.*
        ,c.ActivityDte AS Date1
        ,d.ActivityDte AS Date2
        ,e.ActivityDte AS Date3
FROM Tbl1 a
LEFT JOIN Tbl2 c
    ON a.IdNbr = c.IdNbr
    AND c.ActivityDte = (SELECT MAX(ActivityDte) AS MaxActivityDte
                        FROM Tbl2
                        WHERE IdNbr = a.IdNbr
                        AND PendingId = (SELECT MAX(PendingId) 
                                        FROM Tbl2
                                        WHERE IdNbr = a.IdNbr)
                        )
LEFT JOIN Tbl2 d
    ON a.IdNbr = d.IdNbr
    AND d.ActivityDte = (SELECT MAX(ActivityDte) AS MaxActivityDte
                        FROM Tbl2
                        WHERE IdNbr = a.IdNbr
                        AND PendingId = (SELECT MAX(PendingId) - 1
                                        FROM Tbl2
                                        WHERE IdNbr = a.IdNbr)
                        )
LEFT JOIN Tbl2 e
    ON a.IdNbr = e.IdNbr
    AND e.ActivityDte = (SELECT MAX(ActivityDte) AS MaxActivityDte
                        FROM Tbl2
                        WHERE IdNbr = a.IdNbr
                        AND PendingId = (SELECT MAX(PendingId) -2
                                        FROM Tbl2
                                        WHERE IdNbr = a.IdNbr)

0 个答案:

没有答案