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)。
感謝您的幫助提前。
謝謝你回答我的詢問。由於ProductMovement表上的記錄可能在幾天內達到數百萬次,因此我對查詢的性能有點擔心。它可能不適合更大的數據庫記錄。我會盡力而爲。再次感謝 –
如果這是一個問題,請確保在ProductMovement上有一個索引,或者使用ProductId和EffectiveDate作爲關鍵或非集羣來使用相同的密鑰,但一定要包含位置 – MWillemse