我有一个具有以下各列的表A:

Status varchar
StateCode bit
OpportunityID int


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

我该如何完成?

任何想法和建议都将受到赞赏!

最佳答案

您可以在case语句中使用count,以便仅计算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



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


不,如果您有一个同时具有OpportunityIDStateCode1,那将不是真的。

例如:

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

关于sql-server-2008 - 根据条件按COUNT个分组,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/9765008/

10-11 01:15