2013-03-08 51 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

相關問題