SQL执行自联接以按日期检索当前和前一个记录

时间:2016-12-08 10:44:54

标签: sql-server-2008

我一直试图将当前和以前的记录检索为一行。我需要在当前记录之前获得直接记录,以比较两行的位置。

Select 
    CurrentMovement.Location, CurrentMovement.EffectiveDate
  , PreviousMovement.Location, PreviousMovement.EffectiveDate 
From Product product
Inner join ProductMovement CurrentMovement ON product.Id = CurrentMovement.ProductId
    And CurrentMovement.EffectiveDate = (Select Max(EffectiveDate)
                                         From ProductMovement
                                         Where ProductId = product.ProductId)
Inner join ProductMovement PreviousMovement ON PreviousMovement.ProductId = CurrentMovement.ProductId
    And PreviousMovement.EffectiveDate < CurrentMovement.EffectiveDate
Where CurrentMovement.Locations != PreviousMovement.Location

我能够在CurrentMovement内连接上检索当前记录。

问题是确定下一个内部联接的上一个记录,因为我需要检索小于CurrentMovement.EffectiveDate的先前记录的Max(EffectiveDate)。

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

诀窍是分配顺序行号并使用此行号连接。像这样:

WITH PM AS(
    SELECT *
        , RN = ROW_NUMBER() OVER(PARTITION BY ProductId ORDER BY EffectiveDate DESC)
    FROM ProductMovement
)
Select 
    PMC.Location, PMC.EffectiveDate
  , PMP.Location, PMP.EffectiveDate 
From Product AS P
    INNER join PM AS PMC
        ON P.Id = PMC.ProductId
        AND PMC.RN = 1
    LEFT JOIN PM ON PMP
        ON P.Id= PMP.ProductId
        AND PMP.RN - 1 = PMC.RN