GROUP BY 是 SQL 中用于对数据进行分组的一个子句,通常与聚合函数(如 COUNT、SUM、AVG、MAX、MIN 等)一起使用。GROUP BY 子句将结果集中的记录按照一个或多个列进行分组,然后对每个组应用聚合函数。
以下是 GROUP BY 的基本用法:
SELECT column1, column2, ..., aggregate_function(column)
FROM table_name
WHERE condition
GROUP BY column1, column2, ...;
假设有一个名为 orders 的表,结构如下:
| order_id | customer_id | order_date | total_amount |
|---|---|---|---|
| 1 | 101 | 2023-01-01 | 100.00 |
| 2 | 102 | 2023-01-02 | 150.00 |
| 3 | 101 | 2023-01-03 | 200.00 |
| 4 | 103 | 2023-01-04 | 120.00 |
| 5 | 102 | 2023-01-05 | 180.00 |
customer_id 分组,计算每个客户的订单总金额SELECT customer_id, SUM(total_amount) AS total_spent
FROM orders
GROUP BY customer_id;
结果:
| customer_id | total_spent |
|---|---|
| 101 | 300.00 |
| 102 | 330.00 |
| 103 | 120.00 |
order_date 分组,计算每天的订单数量SELECT order_date, COUNT(*) AS order_count
FROM orders
GROUP BY order_date;
结果:
| order_date | order_count |
|---|---|
| 2023-01-01 | 1 |
| 2023-01-02 | 1 |
| 2023-01-03 | 1 |
| 2023-01-04 | 1 |
| 2023-01-05 | 1 |
customer_id 和 order_date 分组,计算每个客户每天的订单总金额SELECT customer_id, order_date, SUM(total_amount) AS total_spent
FROM orders
GROUP BY customer_id, order_date;
结果:
| customer_id | order_date | total_spent |
|---|---|---|
| 101 | 2023-01-01 | 100.00 |
| 101 | 2023-01-03 | 200.00 |
| 102 | 2023-01-02 | 150.00 |
| 102 | 2023-01-05 | 180.00 |
| 103 | 2023-01-04 | 120.00 |
GROUP BY 子句中出现的列必须在 SELECT 子句中明确列出。GROUP BY 通常与聚合函数一起使用,用于对每个组进行计算。WHERE 子句用于过滤数据,而 HAVING 子句用于对分组后的数据进行过滤。希望这些示例和解释能帮助你更好地理解和使用 GROUP BY 子句。
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。