2013-03-08 58 views
0

以下是我的查询,它返回从年至日的策略计数。我想知道如何处理一个只会影响“活跃”状态的陈述。如何影响具有多个状态的where子句中的单个状态

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 

下面是电流输出:

enter image description here

我试图做

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

应该只考虑活动状态?你的数量? – 2013-03-08 21:18:02

+0

我想统计所有有原始报价编号和nsid数据的活动策略,但我的筛选也影响了我的报价计数并被拒绝。 – user2146212 2013-03-08 21:23:40

回答

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 
+0

谢谢!我将不得不对它进行调整,以查看它是否适用于数据库中的其他所有内容。 – user2146212 2013-03-08 22:14:21