我的SQL查詢應返回以前的記錄(索賠)。 Previous表示它具有不同的主鍵(idData),相等的SSN_Number和更早的Received_Date。問題是Received_Date可能相等,所以我必須尋找另一列。優先級應與排序順序相同。 我在做什麼錯誤,因爲查詢返回兩個ID的另一個記錄(兩個索賠都是以前的對方)?我的SQL有什麼問題? (查找「前一個」記錄)
我的兩個測試,記錄如下: same SSN_Number http://www.bilder-hochladen.net/files/4709-kr.jpg
的SQL查詢是這樣的:
SELECT TOP (1) Claim.idData AS ClaimID,
PrevClaim.idData AS PrevClaimID
FROM tabData AS Claim
INNER JOIN tabData AS PrevClaim
ON Claim.SSN_Number = PrevClaim.SSN_Number
AND Claim.idData <> PrevClaim.idData
AND (Claim.Received_Date > PrevClaim.Received_Date
OR Claim.Claim_Creation_Date > PrevClaim.Claim_Creation_Date
OR Claim.Repair_Completion_Date >
PrevClaim.Repair_Completion_Date
OR Claim.Claim_Submitted_Date >
PrevClaim.Claim_Submitted_Date)
WHERE (Claim.idData = @claimID)
ORDER BY PrevClaim.Received_Date DESC,
PrevClaim.Claim_Creation_Date DESC,
PrevClaim.Repair_Completion_Date DESC,
PrevClaim.Claim_Submitted_Date DESC
編輯:根據Mongus傍回答這是正確的SQL:
SELECT TOP (1) Claim.idData AS ClaimID, PrevClaim.idData AS PrevClaimID
FROM tabData AS Claim INNER JOIN tabData AS PrevClaim
ON Claim.SSN_Number = PrevClaim.SSN_Number
AND Claim.idData <> PrevClaim.idData
AND (Claim.Received_Date > PrevClaim.Received_Date
OR Claim.Received_Date = PrevClaim.Received_Date AND Claim.Claim_Creation_Date > PrevClaim.Claim_Creation_Date
OR Claim.Received_Date = PrevClaim.Received_Date AND Claim.Claim_Creation_Date = PrevClaim.Claim_Creation_Date AND Claim.Repair_Completion_Date > PrevClaim.Repair_Completion_Date
OR Claim.Received_Date = PrevClaim.Received_Date AND Claim.Claim_Creation_Date = PrevClaim.Claim_Creation_Date AND Claim.Repair_Completion_Date = PrevClaim.Repair_Completion_Date AND Claim.Claim_Submitted_Date > PrevClaim.Claim_Submitted_Date)
WHERE (Claim.idData = @claimID)
ORDER BY PrevClaim.Received_Date DESC,
PrevClaim.Claim_Creation_Date DESC,
PrevClaim.Repair_Completion_Date DESC,
PrevClaim.Claim_Submitted_Date DESC
謝謝。這是行得通的。我認爲它一定是這樣的,但我對此感到困惑:) – 2010-07-16 15:34:15