您可以在您的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