Skip to content

GROUP BY

一句话解释

GROUP BY 分组行 那个 share 相同值 in specified 列, 所以 aggregate 函数 compute result 每分组.

用大白话说

GROUP BY divides rows into groups based on the values in one or more columns, then applies aggregate functions to each group separately. This lets you answer questions like "如何许多顺序做每个用户位置?" or "什么是平均 salary 每 department?"

When you use GROUP BY, every column in the SELECT that is not inside an aggregate function must appear in the GROUP BY clause. This is because the database needs to know how to group the non-aggregated columns.

To filter groups (after aggregation), use HAVING — WHERE filters rows before grouping, HAVING filters groups after.

示例

sql
-- Number of orders and total per user
SELECT user_id, COUNT(*) AS order_count, SUM(total) AS total_spent
FROM orders
GROUP BY user_id;

行是 分组通过 user_id, 然后 COUNT and SUM 是 computed for 每个分组.

相关术语

相关资源

相关课程

  • GROUP BY

    学习如何 分组 and aggregate 数据.

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回术语表