0

这是我的查询,它返回从年初至今的政策计数。我想知道如何处理仅影响等于“活动”状态的语句。

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_* 仅针对活动状态?任何线索或指针将不胜感激。

4

1 回答 1

1

在 SELECT 中使用 CASE 语句返回 1 或 0,然后对返回的值求和。

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
于 2013-03-08T21:26:27.563 回答