根据相同PolicyNumber

时间:2017-08-18 21:41:08

标签: sql sql-server sum

我需要创建一个列Type。 如果PolicyNumber的结果为Premium,则列Type的值应为1             和 如果同一Premium的{​​{1}}的和是< = 0,则PolicyNumber

的值应为1
PolicyNumber

理想的结果:

PolicyNumber  AgentName   Premium   Transaction
   A           Brien       1,000     New Business
   A           Brien      -1,000     Cancelled
   B           Michael     500       New Business
   C           David       600       New Business
   D           Tom         800       New Business
   D           Tom        -800       Endorsement

3 个答案:

答案 0 :(得分:3)

使用案例我们可以通过使用或相关的查询选择来设置此值。

SELECT PolicyNumber
     , AgentName
     , Premium
     , [Transaction]
     , Case when Premium < 0 OR (SELECT sum(B.Premium) 
                                 FROM tblName B 
                                 WHERE B.PolicyNumber = A.PolicyNumber) <= 0 then 1 else 0 end as Type
FROM tblName A

虽然上面逐行选择可能会很慢。可能最好在子查询中获得总数。

SELECT A.PolicyNumber
     , A.AgentName
     , A.Premium
     , A.[Transaction]
     , Case when A.Premium < 0 OR B.SP <=0 then 1 else 0 end as Type
FROM tblName A
INNER JOIN (SELECT sum(Premium) SP, PolicyNumber 
            FROM  tblName 
            GROUP BY PolicyNumber) B
 on A.PolicyNumber = B.Policy_Number

答案 1 :(得分:2)

select t.*, case when Premium < 0 then 1 when s <= 0 then 1 else 0 end as type from (
    select your_table.*, sum(Premium) over(partition by PolicyNumber) as s from your_table
) t

答案 2 :(得分:2)

试试这个(sql server 2008 +)

With policyData as(
Select policyNumber,agentName,Premium, transaction, sum(premium) over (partition by policyNumber) sumPremium from yourTable
)
Select policyNumber, agentName, premium, transaction, case when premium<0 or sumPremium<=0 then 1 Else 0 End as type from policyData