您可以在您的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
同時具有StateCode
爲1
和0
是真實的。
例:
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