2012-03-19 63 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