[英]Oracle SQL group by then sum
我有一張CUST_LOG
表,下面有數據。
+----+---------+--------+
| ID | CUST_ID | STATUS |
+----+---------+--------+
| 1 | 1 | 1 |
| 2 | 1 | 2 |
| 3 | 2 | 2 |
| 4 | 3 | 3 |
| 5 | 1 | 1 |
| 6 | 1 | 2 |
| 7 | 1 | 3 |
| 8 | 2 | 1 |
| 9 | 2 | 2 |
+----+---------+--------+
我應該如何在上面的 select 得到以下結果? 我想按CUST_ID
分組,然后按CUST_ID
對每個狀態計數求和? 我使用OUTER JOIN
但不起作用。
+---------+----------+----------+----------+
| CUST_ID | STATUS_1 | STATUS_2 | STATUS_3 |
+---------+----------+----------+----------+
| 1 | 2 | 2 | 1 |
| 2 | 1 | 2 | 0 |
| 3 | 0 | 0 | 1 |
+---------+----------+----------+----------+
我發現的唯一方法是使用UNION
子句作為下面的sql,但是如果有很多狀態就太復雜了。
select CUST_ID, SUM(STATUS_1) as STATUS_1, SUM(STATUS_2) as STATUS_2, SUM(STATUS_3) as STATUS_3 from (
select CUST_ID, COUNT(ID) as STATUS_1, 0 as STATUS_2, 0 as STATUS_3 from CUST_LOG where STATUS = 1 group by CUST_ID
union
select CUST_ID, 0 as STATUS_1, COUNT(ID) as STATUS_2, 0 as STATUS_3 from CUST_LOG where STATUS = 2 group by CUST_ID
union
select CUST_ID, 0 as STATUS_1, 0 as STATUS_2, COUNT(ID) as STATUS_3 from CUST_LOG where STATUS = 3 group by CUST_ID
) group by CUST_ID;
嘗試以下,這里是演示。
select
cust_id,
sum(case when status = 1 then 1 else 0 end) status_1,
sum(case when status = 2 then 1 else 0 end) status_2,
sum(case when status = 3 then 1 else 0 end) status_3
from cust_log
group by
cust_id
order by
cust_id
Output:
| cust_id | status_1 | status_2 | status_3 |
| ------- | -------- | -------- | -------- |
| 1 | 1 | 1 | 0 |
| 2 | 0 | 1 | 0 |
| 3 | 0 | 0 | 1 |
您正在尋找 pivot 查詢:
SELECT
CUST_ID,
CASE WHEN COUNT(CASE WHEN STATUS = 1 THEN 1 END) > 0 THEN 1 ELSE 0 END AS STATUS_1,
CASE WHEN COUNT(CASE WHEN STATUS = 2 THEN 1 END) > 0 THEN 1 ELSE 0 END AS STATUS_2,
CASE WHEN COUNT(CASE WHEN STATUS = 3 THEN 1 END) > 0 THEN 1 ELSE 0 END AS STATUS_3
FROM CUST_LOG
GROUP BY
CUST_ID
ORDER BY
CUST_ID;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.