基于条件的组中的COUNT

Sai*_*and 2 sql-server-2008

我有一个表A,其中包含以下列:

Status varchar
StateCode bit
OpportunityID int
Run Code Online (Sandbox Code Playgroud)

所以,如果我这样做:SELECT count(distinct opportunityID) from table A group by Status我得到了计数.现在在同一个查询中,我想添加另一个名为CurrentCount和HistoricalCount的列.当前计数是特定Status和StateCode = 0的不同opportunityID的计数,HistoricalCount是特定Status和StateCode = 1的不同opportunityID的计数.换句话说,Count =(CurrentCount + HistoricalCount).

我怎么做到这一点?

任何想法和建议都非常感谢!

Mik*_*son 7

您可以casecount语句中使用a ,以便只计算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
Run Code Online (Sandbox Code Playgroud)

换句话说,Count =(CurrentCount + HistoricalCount).

不,如果你有一个OpportunityID同时具有StateCodeas 10.

例如:

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
Run Code Online (Sandbox Code Playgroud)

结果:

Status     Count       CurrentCount HistoricalCount
---------- ----------- ------------ ---------------
Status1    2           2            1
Status2    2           0            2
Run Code Online (Sandbox Code Playgroud)