PostgreSQL GROUP BY 子句
GROUP BY
GROUP BY
子句将具有相同值的行分组为摘要行,如 "查找每个国家/地区的客户数量"。
GROUP BY
子句通常与聚合函数(如 COUNT()
,MAX()
,MIN()
,SUM()
,AVG()
)一起使用,以将结果集分组为一列或多列。
实例
列出每个国家/地区的客户数量:
SELECT COUNT(customer_id), country
FROM customers
GROUP BY country;
GROUP BY 与 JOIN 一起使用
下面的 SQL 语句列出了每个客户的订单数量:
实例
SELECT customers.customer_name, COUNT(orders.order_id)
FROM orders
LEFT JOIN customers ON orders.customer_id = customers.customer_id
GROUP BY customer_name;