我的SQL-Query应返回先前的记录(Claim)。 Previous表示它具有不同的主键(idData),相等的SSN_Number和较早的Received_Date。问题是Received_Date可能相等所以我必须寻找另一列。优先级应与Sort-Order相同。 我做错了什么,因为查询返回两个ID的另一个记录(两个声明是彼此之前的声明)?
我的两个测试记录如下: same SSN_Number http://www.bilder-hochladen.net/files/4709-kr.jpg
SQL-Query是这样的:
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 Pong的回答,这是正确的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
答案 0 :(得分:3)
问题是,如果其中任何一个日期小于另一个日期,则您将返回上一条记录。
这两个记录至少有一个日期少于另一个记录,因此它们会返回每个记录。
根据您指定的内容,您可能需要以下内容:
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)
看起来很可怕,但那就是SQL吧!
答案 1 :(得分:1)
看起来你得到了两个记录,因为
Claim.Repair_Completion_Date > PrevClaim.Repair_Completion_Date
对于第二个是正确的,并且OR组中的其他三个子句对于第一个是真的。
您可能不希望在完成日期进行比较;也许只是在另一个领域,比如Claim_Submitted_Date?
答案 2 :(得分:1)
第一行的REPAIR_COMPLETION_DATE
早于第二行,这意味着它将满足JOIN条件Claim.Repair_Completion_Date > PrevClaim.Repair_Completion_Date
,从而有资格作为“之前”的声明。