我有一张这样的表,
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对其进行分组,但结果无关紧要任何人都可以帮我解决
答案 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