SQL Count选择性文本

时间:2018-05-07 12:28:32

标签: sql sql-server

我有一张这样的表,

enter image description here

我想要的是各个ID的流程计数, enter image description here

DDL:

declare @t table (process char(3), identifyingId int)
insert into @t values
('abc',123),('abc',345),('abc',567),('abc',345),('cdf',123),('cdf',123)

我尝试Select Count(Process)并按ID对其进行分组,但结果无关紧要任何人都可以帮我解决

3 个答案:

答案 0 :(得分:7)

执行条件聚合;

select Id,
       sum(case when Process = 'ABC' then 1 else 0 end) [Count(ABC)],
       sum(case when Process = 'CDF' then 1 else 0 end) [Count(CDF)]
from table t
where Process in ('ABC', 'CDF')
group by Id;

答案 1 :(得分:1)

我将使用窗口函数和PIVOT

来填充我的解决方案
select identifyingId, abc [count(abc)], cdf [count(cdf)] from (
    select process, identifyingId, COUNT(*) over (partition by process, identifyingId) [cnt] from @t
) [t] pivot (
    max([cnt]) for process in (abc, cdf)
) [u]

答案 2 :(得分:1)

以稍微不同的方式进行条件聚合

select identifyingId,
     Sum (case when Process = 'ABC' then  1 else 0 end)  [Count(ABC)],
     Sum (case when Process = 'CDF' then 1 else 0 end)  [Count(CDF)]
from  @t
group by identifyingId