简单分组

订单表

顾客 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