如何基于策略级SQL Server 2012上的另一列创建列

时间:2019-02-13 17:49:28

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

我有这样的桌子:

declare @ClaimType table (PolicyNumber varchar(50), QuoteID int,  CoverageType varchar(50))

insert into @ClaimType values   ('00001',1, 'CSO'),
                                ('00001',2, 'CPL'),
                                ('00001',3, 'EO'),
                                ('00002',1, 'CPL'),
                                ('00002',2, 'CGL')

select QuoteID,
        PolicyNumber,      
        CoverageType
from @ClaimType
go

enter image description here

我需要创建列'AnnualStatementLine'并根据CoverageType在其中生成值

在策略级别,我需要检查CoverageType是否具有“ CGL”值。如果不是,则输入“ 17.1”,否则输入“ 19.1”

因此CoverageType 'CGL'没有PolicyNumber 00001,因此AnnualStatementLine应该是17.1

对于策略00002,其中一个值具有“ CGL”,因此需要为“ 19.1”

是否可以在单个select语句中实现?

结果应如下所示:

enter image description here

谢谢

2 个答案:

答案 0 :(得分:0)

您可以使用EXISTS

SELECT ct.*,
       (CASE WHEN EXISTS (SELECT 1 
                          FROM @ClaimType ct1 
                          WHERE ct1.PolicyNumber = ct.PolicyNumber AND ct1.CoverageType = 'CGL'
                         ) 
             THEN '19.1' 
             ELSE '17.1'
        END) AS AnnualStatementLine
FROM @ClaimType ct;

答案 1 :(得分:0)

您可以使用IN子句尝试以下查询。

declare @ClaimType table (PolicyNumber varchar(50), QuoteID int,  CoverageType varchar(50))

insert into @ClaimType values   ('00001',1, 'CSO'),
                                ('00001',2, 'CPL'),
                                ('00001',3, 'EO'),
                                ('00002',1, 'CPL'),
                                ('00002',2, 'CGL')

select QuoteID,
        PolicyNumber,      
        CoverageType,
        case when PolicyNumber IN (Select PolicyNumber from @ClaimType where CoverageType = 'CGL') then 19.1
        else 17.1 end as AnnualStatementLine
from @ClaimType

Demo Link