如何检查索赔人之一是否具有状态0并基于该状态分配索赔状态

时间:2019-04-01 23:01:34

标签: sql sql-server tsql sql-server-2012

每个索赔可以有多个索赔人。 如果这些索赔者中至少有一个拥有'Open'

,则将其视为ClaimantStatus = 0

因此,我需要检索“索赔级别”(不是“索赔人”)上的数据,并创建列ClaimStatus,以表明索赔是Open还是Closed

对于每个ClaimID,我需要检查是否至少有一个索偿人拥有ClaimantStatus = 0(公开),如果为true,则列ClaimStatus应为= {{1} },否则应为= 'Open'

'Closed'

正确答案应该是这样的:

enter image description here

2 个答案:

答案 0 :(得分:2)

看起来简单的GROUP BY就足够了。 如果至少有一个Claim的ClaimantStatus = 0,则Claimant是打开的,我们可以使用MIN来确定。在这里,我们依靠ClaimantStatus只有01的值。

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