簡單分組

訂單表

顧客 ID 產品編號 數量 價錢
1 2 100
1 3 2 200
1 4 1 500
2 1 4 50
3 6 700

按特定列分組時,僅返回此列的唯一值。

SELECT customerId
FROM orders
GROUP BY customerId;

返回值:

顧客 ID
1
2
3

count() 這樣的聚合函式適用於每個組而不是整個表:

SELECT customerId, 
       COUNT(productId) as numberOfProducts,
       sum(price) as totalPrice
FROM orders
GROUP BY customerId;

返回值:

顧客 ID numberOfProducts totalPrice
1 3 800
2 1 50
3 1 700