我在 SQL Server 中有如下表。
| 行程_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_和_P3 |
有人可以幫助我如何總結在 SQLin條件和group by子句下使用的結果并將其顯示在輸出中嗎?
先感謝您。
uj5u.com熱心網友回復:
如果您真的只想要那個單記錄結果集,請洗掉該GROUP BY子句:
SELECT COUNT(Process_ID) AS Process_Count, 'P2_and_P3' AS Process_Type
FROM yourTable
WHERE Process_Type IN ('P2', 'P3');
相反,如果您可能想要查看所有行程型別組,但將P2和P3存盤在一起,則使用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;
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/422592.html
標籤:
