目前我有一個訂單表,每月格式化為一行:
| ID | 訂單_月 | 訂單數 | 訂單總和 |
|---|---|---|---|
| 111 | 2021-07 | 5 | 50 |
| 111 | 2021-08 | 10 | 50 |
| 111 | 2021-09 | 1 | 100 |
| 222 | 2021-07 | 8 | 80 |
| 222 | 2021-08 | 2 | 50 |
| 222 | 2021-09 | 1 | 80 |
有沒有辦法格式化 SQL 查詢,以便每個輸出有 1 行id,而其他值作為列添加?例如:
| ID | 2021-07_order_count | 2021-07_order_sum | 2021-08_order_count | 2021-08_order_sum | 2021-09_order_count | 2021-09_order_sum |
|---|---|---|---|---|---|---|
| 111 | 5 | 50 | 10 | 50 | 1 | 100 |
| 222 | 8 | 80 | 2 | 50 | 1 | 80 |
我想我很接近以下查詢:
SELECT
merchant_id,
(CASE WHEN order_month = '2021-07' THEN order_count ELSE 0 END) as '2021-07-orderCount',
(CASE WHEN order_month = '2021-07' THEN order_sum ELSE 0 END) as '2021-07-orderSum',
(CASE WHEN order_month = '2021-08' THEN order_count ELSE 0 END) as '2021-08-orderCount',
(CASE WHEN order_month = '2021-08' THEN order_sum ELSE 0 END) as '2021-08-orderSum',
(CASE WHEN order_month = '2021-09' THEN order_count ELSE 0 END) as '2021-09-orderCount',
(CASE WHEN order_month = '2021-09' THEN order_sum ELSE 0 END) as '2021-09-orderSum'
FROM orders
ORDER BY id
它正在創建一個單獨的列并在每列中放置正確的值。

但是,當我嘗試按 Id 分組時,它只顯示第一個結果:

謝謝你。
uj5u.com熱心網友回復:
您需要條件聚合:
SELECT id,
MAX(CASE WHEN order_month = '2021-07' THEN order_count ELSE 0 END) `2021-07-orderCount`,
MAX(CASE WHEN order_month = '2021-07' THEN order_sum ELSE 0 END) `2021-07-orderSum`,
MAX(CASE WHEN order_month = '2021-08' THEN order_count ELSE 0 END) `2021-08-orderCount`,
MAX(CASE WHEN order_month = '2021-08' THEN order_sum ELSE 0 END) `2021-08-orderSum`,
MAX(CASE WHEN order_month = '2021-09' THEN order_count ELSE 0 END) `2021-09-orderCount`,
MAX(CASE WHEN order_month = '2021-09' THEN order_sum ELSE 0 END) `2021-09-orderSum`
FROM orders
GROUP BY id
ORDER BY id;
請參閱演示。
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/361351.html
標籤:sql sqlite 通过...分组 最大限度 条件聚合
上一篇:在插入SQLite之前檢查表B中的日期是否在表A中的日期之間
下一篇:選擇一年SQLITE的天數表
