SaiBand
SaiBand

Reputation: 5355

COUNT in group by based on a condition

I have a table A with the following columns:

Status varchar
StateCode bit
OpportunityID int

so if i do: SELECT count(distinct opportunityID) from table A group by Status I get the count. Now in the same query I want to add another columns called CurrentCount and HistoricalCount. The current count is the count of distinct opportunityID for a particular Status and StateCode = 0 and the HistoricalCount is the count of distinct opportunityID for a particular Status and StateCode = 1. In other words Count = (CurrentCount + HistoricalCount ).

How do I accomplish this ??

Any ideas and suggestions are well appreciated !

Upvotes: 2

Views: 4206

Answers (1)

Mikael Eriksson
Mikael Eriksson

Reputation: 138960

You can use a case in your count statements so you only count where StateCode has the desired value.

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

In other words Count = (CurrentCount + HistoricalCount ).

No, that will not be true if you have a OpportunityID that has both StateCode as 1 and 0.

Ex:

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

Result:

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

Upvotes: 7

Related Questions