如何不选择具有基于列名称的优先级的记录

时间:2016-09-22 23:31:43

标签: sql-server tsql case

我选择的其中一列是PolicyType,其条件是TransactionType = 'Policy'。 但有时相同的Insured可以具有相同的TransactionType值,但具有不同的PolicyType值。因此,如果我使用相同的TransactionTypePolicyType具有相同的保险,那么如何确定优先级并选择具有PolicyType ='Rewrite'的记录并忽略具有PolicyType='New Business'的记录? 应该是简单的CASE陈述,但我很困惑 enter image description here

SELECT   CAST(YEAR(EffectiveDate) as CHAR(4))+'/'+ CAST(MONTH(EffectiveDate) AS VARCHAR(2)) AS YearMonth,
         Insured, 
        PolicyNumber,
        EffectiveDate,
        PolicyType,
        TransactionType,
        SUM(Premium) as Premium,
        ExperienceMod,
        ISNULL(ScheduleMod,0) as ScheduleMod,
        TerritoryMod,
        ISNULL(EffectiveMod,0) as EffectiveMod

FROM ProductionReportMetrics
WHERE EffectiveDate >=DateAdd(yy, -1, DATEADD(d, 1, EOMONTH(GETDATE()))) AND EffectiveDate <= EOMONTH(GETDATE())
        AND CompanyLine = 'Arch Insurance Company' AND Insured <>'Jerry''s Test' AND TransactionType = 'Policy' --and  PolicyNumber ='ZAWCI2517900'
GROUP BY Insured,
        PolicyNumber,
        PolicyType,
        TransactionType,
        EffectiveDate,
        experienceMod,ScheduleMod,TerritoryMod,EffectiveMod, Premium,EffectiveDate
ORDER BY YEAR(EffectiveDate), (MONTH(EffectiveDate)), PolicyType

1 个答案:

答案 0 :(得分:2)

检查您的示例数据后,我认为policyType列的优先级为rewrite > renewal > new business。 :)

因此,解决方案就是这样,请相应更改代码:

--Create table
create table #test (id int identity(1,1), name varchar(10), trantype varchar(10) default 'policy', policytype varchar(50))

--insert sample data
insert #test (name,trantype,policytype)
select 'abc','policy','new business'
union all
select 'abc','policy','rewrite'
union all
select 'AA','policy','new business'
union all
select 'BB','policy','new business'
union all
select 'BB','policy','rewrite'
union all
select 'CC','policy','rewrite'

select * from #test

--solution
select * from 
(select *, row_number()over(partition by name,trantype order by policytype desc) as rid 
 from #test
) as b
where b.rid = 1

<强>结果:

(1)如果指定的new business只有insured,那么它将被选中;

(2)如果某个new business同时有rewriteinsured,则只会选择重写。

enter image description here