Group By Condition 下的结果求和

Sum the result under Group By Condition

我在 SQL 服务器中有如下 table。

Process_ID Process_Type
011 P1
012 P1
013 P2
014 P2
015 P3
016 P3

我想同时获取进程类型 P2 和 P3 的进程 ID 计数。我使用了如下查询:

select count(Process_ID) as Process_Count, Process_Type
from Process_Table
where Process_type in ('P2','P3')
group by Process_Type;

结果显示:

Process_Count Process_Type
2 P2
2 P3

但我需要:

Process_Count Process_Type
4 P2_and_P3

有人可以帮助我如何将在 SQL in 条件和 group by 子句下使用的结果相加并显示在输出中吗?

提前致谢。

如果您真的只想要一条记录的结果集,则删除 GROUP BY 子句:

SELECT COUNT(Process_ID) AS Process_Count, 'P2_and_P3' AS Process_Type
FROM yourTable
WHERE Process_Type IN ('P2', 'P3');

如果相反,您可能想要查看所有进程类型组,但将 P2P3 组合在一起,则使用 CASE 表达式聚合:

SELECT
    CASE WHEN Process_Type IN ('P2', 'P3')
         THEN 'P2_and_P3' ELSE Process_Type END AS Process_Type,
    COUNT(Process_ID) AS Process_Count
FROM yourTable
GROUP BY
    CASE WHEN Process_Type IN ('P2', 'P3') THEN 'P2_and_P3' ELSE Process_Type END;