having 子句
在 sql 中增加 having 子句原因是,where 关键字无法与合计函数一起使用。
sql having 语法
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
sql having 实例
我们拥有下面这个 “orders” 表:
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 |
现在,我们希望查找订单总金额少于 2000 的客户。
我们使用如下 sql 语句:
select customer,sum(orderprice) from orders group by customer having sum(orderprice)<2000
结果集类似:
customer | sum(orderprice) |
---|---|
carter | 1700 |
现在我们希望查找客户 “bush” 或 “adams” 拥有超过 1500 的订单总金额。
我们在 sql 语句中增加了一个普通的 where 子句:
select customer,sum(orderprice) from orders where customer='bush' or customer='adams' group by customer having sum(orderprice)>1500
原文链接:http://www.sysoft.top/article.aspx?id=3738