2016-09-22 16 views
0

Imのピックアップ列の1つはPolicyTypeで、その条件はTransactionType = 'Policy'です。 しかし、同じInsuredは同じTransactionType値を持つことができますが、異なるPolicyType値を持つことがあります。だから私は同じTransactionTypeと同じ被保険者を持っているが、異なるPolicyType - どのようにプライオリティとPolicyType='New Business'でそれを無視して、ポリシータイプ='Rewrite'を持つレコードを選択することができますか? は単純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 

結果:のみnew businessは、指定されたinsuredにあった場合

(1)、それはなりますが選択された。

(2)new businessrewriteの両方が特定の場合はinsuredの場合は、書き換えのみが選択されます。

enter image description here

+0

素晴らしい!!!!!!!!!!非常に@ダンスヘンリーありがとう – Oleg

関連する問題