使用GroupBy Query计数

时间:2016-05-26 09:36:56

标签: sql sql-server

以下是2个表格 -

JOBS
JobID ProcessID Status
j1    p1          Start 
j2    p2          Stop
j3    p2          Running
j4    p1          Start
j4    p1          Stop

表2

PROCESSES
ProcessID  Name    ProcessGroup
P1         P1Name   G1
P2         P2Name   G2
P3         P3Name   G1 

预期结果 -

Process StartCount  StopCount
P1Name      2           1
P2Name      0           1 

我正在尝试使用group by query进行上述输出。

select jobId,p.Name, COUNT(j.j.JobID) as StartCount
from JOBS j,
PROCESSES p
where j.Status = 'Start' and
      j.ProcessID= p.ProcessID
group by j.Status

在单个查询中,我只能获得Start或StopCount的计数。我可以在一个查询中同时获得这两个吗?

1 个答案:

答案 0 :(得分:5)

您可以使用条件聚合

select p.Name, 
       count(case when Status = 'Start' then 1 end) as StartCount,
       count(case when Status = 'Stop' then 1 end) as StopCount
from JOBS j
join PROCESSES p on j.ProcessID = p.ProcessID      
group by p.Name