2016-12-08 34 views
0

我一直在嘗試檢索當前記錄和前一記錄作爲單個行。我需要在當前記錄之前獲得直接記錄以比較兩行的位置。SQL執行自加入以按日期檢索當前記錄和前一個記錄

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)。

感謝您的幫助提前。

回答

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 

+0

謝謝你回答我的詢問。由於ProductMovement表上的記錄可能在幾天內達到數百萬次,因此我對查詢的性能有點擔心。它可能不適合更大的數據庫記錄。我會盡力而爲。再次感謝 –

+0

如果這是一個問題,請確保在ProductMovement上有一個索引,或者使用ProductId和EffectiveDate作爲關鍵或非集羣來使用相同的密鑰,但一定要包含位置 – MWillemse

相關問題