2016-09-22 55 views
0

其中一列Im拾取的是PolicyType,条件是TransactionType = 'Policy'。 但有时相同的Insured可以具有相同的TransactionType值,但具有不同的PolicyType值。所以,如果我有相同的投保TransactionType,但不同PolicyType - 如何优先和选择具有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 

回答

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 businessrewrite都存在某个insured,则只会选择重写。

enter image description here

+0

真棒!!!!!!!!!!非常感谢Dance @ Henry – Oleg

相关问题