MySQL聚合查询
MySQL支持多种聚合查询,包括SUM、COUNT、AVG、MIN、MAX等。
以下是一个示例的表结构和样例数据:
表名:orders
| order_id | customer_id | order_date | amount |
|----------|-------------|------------|--------|
| 1 | 1 | 2022-01-01 | 100 |
| 2 | 1 | 2022-01-02 | 200 |
| 3 | 2 | 2022-01-01 | 150 |
| 4 | 2 | 2022-01-02 | 300 |
1. SUM聚合查询:计算某一列的总和
sql
SELECT SUM(amount) as total_amount
FROM orders;
结果:total_amount=750
2. COUNT聚合查询:计算某一列的数量
sql
SELECT COUNT(order_id) as total_orders
FROM orders;
结果:total_orders=4
3. AVG聚合查询:计算某一列的平均值
sql
SELECT AVG(amount) as avg_amount
FROM orders;
结果:avg_amount=187.5
4. MIN聚合查询:找出某一列的最小值
sql
SELECT MIN(amount) as min_amount
FROM orders;
结果:min_amount=100
5. MAX聚合查询:找出某一列的最大值
sql
SELECT MAX(amount) as max_amount
FROM orders;
结果:max_amount=300
除了上述基本的聚合查询,MySQL还支持其他高级聚合查询,如GROUP BY、HAVING等,可以用于对数据进行分组、筛选等操作。以下是一个示例:
sql
SELECT customer_id, SUM(amount) as total_amount
FROM orders
GROUP BY customer_id
HAVING total_amount > 200;
结果:
| customer_id | total_amount |
|-------------|--------------|
| 1 | 300 |
| 2 | 450 |
这个示例中,首先对orders表按customer_id进行了分组,然后计算每个分组中amount的总和,并筛选出总和大于200的分组。