这是我的查询,它返回年复一年的策略计数。我想知道如何在只影响等于'active'的状态的语句时做一个案例。
select distinct
count(pol3.CT_ID + pol3.CT_NSID) as 'YTD',
pol3.ct_status
from contract pol3
where (pol3.CT_Status = 'Quote' or pol3.ct_status='Active' or pol3.ct_status='Declined')
and Year(pol3.CT_Subscription_Date)>= datediff(year,(DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)), getdate())
group by pol3.ct_status
这是当前的输出:
我试过
select distinct
count(pol3.CT_ID + pol3.CT_NSID) as 'YTD',
pol3.ct_status
from contract pol3
where (pol3.CT_Status = 'Quote' or pol3.ct_status='Active' or pol3.ct_status='Declined')
and CT_ORIGINAL_QUOTE_ID is not null
and CT_ORIGINAL_QUOTE_NSID is not null
and Year(pol3.CT_Subscription_Date)>= datediff(year,(DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)), getdate())
group by pol3.ct_status
这显然是错误的,因为它针对所有三种状态。如何让ct_original_ *仅针对活动状态?任何线索或指针都将受到高度赞赏。
答案 0 :(得分:1)
在SELECT中使用CASE语句返回1或0,然后对返回的值进行SUM。
SELECT pol3.ct_status, SUM(CASE
WHEN ct_status IN ('Declined','Quote') THEN 1 // all of these should count as one policy
WHEN ct_status = 'Active' and CT_ORIGINAL_QUOTE_ID is not null and CT_ORIGINAL_QUOTE_NSID is not null THEN 1 // if data in ID and NSID and active count it
ELSE 0 // all others count as nothing
END)
from contract pol3
where (pol3.CT_Status = 'Quote' or pol3.ct_status='Active' or pol3.ct_status='Declined')
and Year(pol3.CT_Subscription_Date)>= datediff(year,(DATEADD(yy, DATEDIFF(yy,0,getdate()), 0)), getdate())
group by pol3.ct_status