📅  最后修改于: 2023-12-03 15:20:18.627000             🧑  作者: Mango
在SQLite中,GROUP BY子句是用于将查询结果根据一个或多个列进行分组的语句。它通常与聚合函数(如SUM、AVG、COUNT等)一起使用,以便对每个分组执行计算操作。
以下是GROUP BY子句的基本语法:
SELECT 列1, 列2, ..., 聚合函数(列)
FROM 表名
WHERE 条件
GROUP BY 列1, 列2, ...
考虑以下名为"orders"的表格:
| order_id | customer_id | total_amount | | -------- | ----------- | ------------ | | 1 | 100 | 50 | | 2 | 101 | 30 | | 3 | 100 | 20 | | 4 | 102 | 70 | | 5 | 101 | 40 |
SELECT customer_id, SUM(total_amount) as total
FROM orders
GROUP BY customer_id
结果如下:
| customer_id | total | | ----------- | ----- | | 100 | 70 | | 101 | 70 | | 102 | 70 |
SELECT customer_id, COUNT(*) as count
FROM orders
GROUP BY customer_id
HAVING count > 1
结果如下:
| customer_id | count | | ----------- | ----- | | 100 | 2 | | 101 | 2 |
更多关于SQLite GROUP BY子句的详细信息,请参阅官方文档:SQLite GROUP BY