每个索赔可以有多个索赔人。
如果这些索赔者中至少有一个拥有'Open'
ClaimantStatus = 0
因此,我需要检索“索赔级别”(不是“索赔人”)上的数据,并创建列ClaimStatus
,以表明索赔是Open
还是Closed
。
对于每个ClaimID
,我需要检查是否至少有一个索偿人拥有ClaimantStatus = 0
(公开),如果为true,则列ClaimStatus
应为= {{1} },否则应为= 'Open'
'Closed'
正确答案应该是这样的:
答案 0 :(得分:2)
看起来简单的GROUP BY
就足够了。
如果至少有一个Claim
的ClaimantStatus = 0,则Claimant
是打开的,我们可以使用MIN
来确定。在这里,我们依靠ClaimantStatus
只有0
和1
的值。
SELECT
Claims.ClaimID
,COUNT(*) AS NumberOfClaimants
,CASE WHEN MIN(Claimants.ClaimantStatus) = 0
THEN 'Open'
ELSE 'Closed'
END AS ClaimStatus
FROM
@ClaimsTable AS Claims
INNER JOIN @ClaimantsTable AS Claimants ON Claimants.ClaimID = Claims.ClaimID
GROUP BY
Claims.ClaimID
ORDER BY
Claims.ClaimID;
答案 1 :(得分:1)
我认为您要使用Exists
select ClaimID,
(select count (ClaimantName) from @ClaimantsTable ct where ct.ClaimID = c.ClaimID) as NumberOfClaimants,
CASE WHEN EXISTS(SELECT 1
FROM @ClaimantsTable AS claimant
WHERE claimant.ClaimID = c.ClaimID
AND claimant.ClaimantStatus = 0)
THEN 'Open'
ELSE 'Closed' END AS claimStatus
from @ClaimsTable c
根据您的情况,您可能还会考虑分组查询。通过不需要对计数和状态进行两个单独的查找,可以更加有效。这确实要求每项索赔至少有一名索赔人。
SELECT
claim.ClaimId
,COUNT(*) AS NumberOfClaimants
,CASE WHEN SUM(CASE WHEN claimant.ClaimantStatus = 0 THEN 1 ELSE 0 END) > 0 THEN 'Open' ELSE 'Closed' END AS claimStatus
FROM
@ClaimsTable AS claim
INNER JOIN @ClaimantsTable AS claimant
ON claim.ClaimID = claimant.ClaimID
GROUP BY
claim.ClaimID