給定一張表 tab,欄位包含 id、in、out、index (皆為 integer)。需求如下:
index = 2 的資料。id 的資料合併,in、out 欄位分別加總。in + out 總和由大到小排序。| id | in | out | index |
|---|---|---|---|
| 1 | 10 | 12 | 2 |
| 2 | 9 | 8 | 2 |
| 3 | 12 | 8 | 3 |
| 1 | 9 | 9 | 3 |
| 1 | 12 | 0 | 3 |
| 2 | 5 | 18 | 2 |
| 2 | 20 | 0 | 2 |
標準 SQL 聚合查詢即可滿足:
SELECT
id,
SUM([in]) AS [in], -- in 是保留字,需加方括號或雙引號
SUM([out]) AS [out] -- out 同理
FROM tab
WHERE [index] = 2 -- index 也是保留字
GROUP BY id
ORDER BY (SUM([in]) + SUM([out])) DESC;
-- 或簡寫:ORDER BY [in] + [out] DESC (別名在 ORDER BY 可用)
index = 2,剩 id 1、2 的共 4 筆。in、out 分別加總。
| id | in | out |
|---|---|---|
| 2 | 34 | 26 |
| 1 | 10 | 12 |
in、out、index 皆為 SQL 保留字,務必使用方括號 [] (SQL Server) 或雙引號 "" (標準/PostgreSQL) 包裹。(index, id) 上建立複合索引,可加速篩選與分組。善用 WHERE 篩選、GROUP BY 分組、SUM() 聚合、ORDER BY 排序四大基礎子句組合,即可輕鬆解決此類「分組彙總 + 自訂排序」的經典報表需求。