SQL GROUP BY
合计函数常常需要添加 GROUP BY语句
合计函数有:AVG()、COUNT()、FIRST()、LAST()、MAX()、IN()、SUM()......
GROUP BY 语句用于结合合计函数,根据一个或多个列对结果进行分组
语法
SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name
以下表为例
O_Id | OrderDate | OrderPrice | Customer |
---|---|---|---|
1 | 2008/12/29 | 1000 | Bush |
2 | 2008/11/23 | 1600 | Carter |
3 | 2008/10/05 | 700 | Bush |
4 | 2008/09/28 | 300 | Bush |
5 | 2008/08/06 | 2000 | Adams |
6 | 2008/07/21 | 100 | Carter |
实例1,查找每个客户的总金额(总订单),使用GROUP BY对客户进行组合
SELECT Customer, SUM(OrderPrice) FROM Orders GROUP BY Customer
结果如下
Customer | SUM(OrderPrice) |
---|---|
Bush | 2000 |
Carter | 1700 |
Adams | 2000 |
如果省略 GROUP BY
SELECT Customer, SUM(OrderPrice) FROM Orders
结果如下
Customer | SUM(OrderPrice) |
---|---|
Bush | 5700 |
Carter | 5700 |
Bush | 5700 |
Bush | 5700 |
Adams | 5700 |
Carter | 5700 |
显然这个结果不是我们需要的
为什么不能使用上面这条SELECT语句?
因为上面的SELECT 语句制定了两列(Customer 和 SUM(OrderPrice))。“SUM(OrderPrice)”返回一个单独的值(“OrderPrice”列的总计),而“Customer”返回6个值(每个值对应“Orders”表中的每一行)。因此不能得到正确的结果
所以使用GROUP BY语句解决这个问题
GROUP BY应用于一个以上的列
SELECT Customer, OrderDate, SUM(OrderPrice) FROM Orders GROUP BY Customer, OrderDate
SQL HAVING
在SQL 中增加 HAVING子句的原因是,WHERE关键字无法和合计函数一起使用
语法
SELECT column_name, aggregate_function(column_name) FROM table_name WHERE column_name operator value GROUP BY column_name HAVING aggregate_function(column_name) operator value
实例1,还是以上面的 Orders 表为例,查找订单总金额少于 2000的客户
SELECT Customer, SUM(OrderPrice) FROM Orders GROUP BY Customer HAVING SUM(OrderPrice)<2000
结果类似:
Customer | SUM(OrderPrice) |
---|---|
Carter | 1700 |
实例2,现在我们希望查找客户 "Bush" 或 "Adams" 拥有超过 1500 的订单总金额。
在SQL语句中增加一个普通的 WHERE子句
SELECT Customer, SUM(OrderPrice) FROM Orders WHERE Customer=‘Bush‘ OR Customer=‘Adams‘ GROUP BY Customer HAVING SUM(OrderPrice)>1500
结果:
Customer | SUM(OrderPrice) |
---|---|
Bush | 2000 |
Adams | 2000 |
时间: 2024-11-09 02:14:29