2012-03-19 65 views
2

我有以下的列的表答:COUNT組通過基於條件

Status varchar 
StateCode bit 
OpportunityID int 

所以,如果我做的:SELECT count(distinct opportunityID) from table A group by Status我得到的計數。現在在同一個查詢中,我想添加另一個名爲CurrentCount和HistoricalCount的列。當前計數是特定Status和StateCode = 0的不同opportunityID的計數,而HistoricalCount是特定Status和StateCode = 1的不同opportunityID的計數。換句話說Count =(CurrentCount + HistoricalCount)。

我該如何做到這一點?

任何意見和建議,非常感謝!

回答

7

您可以在您的count報表中使用case,因此您只能計算其中StateCode具有所需值。

select Status, 
     count(distinct OpportunityID) as [Count], 
     count(distinct case when StateCode = 1 then OpportunityID end) as CurrentCount, 
     count(distinct case when StateCode = 0 then OpportunityID end) as HistoricalCount 
from YourTable 
group by Status 

換句話說計數=(CURRENTCOUNT + HistoricalCount)。

不,不會,如果你有一個OpportunityID同時具有StateCode10是真實的。

例:

declare @T table 
(
    Status varchar(10), 
    StateCode bit, 
    OpportunityID int 
) 

insert into @T values 
('Status1', 1, 1), 
('Status1', 1, 2), 
('Status1', 0, 2), 
('Status2', 0, 1), 
('Status2', 0, 2) 

select Status, 
     count(distinct OpportunityID) as [Count], 
     count(distinct case when StateCode = 1 then OpportunityID end) as CurrentCount, 
     count(distinct case when StateCode = 0 then OpportunityID end) as HistoricalCount 
from @T 
group by Status 

結果:

Status  Count  CurrentCount HistoricalCount 
---------- ----------- ------------ --------------- 
Status1 2   2   1 
Status2 2   0   2