sql语句having用法
时间: 2023-10-10 07:06:50 浏览: 85
HAVING子句用于在GROUP BY子句之后过滤聚合后的结果集。它允许我们使用聚合函数对分组后的数据进行筛选,类似于WHERE子句用于筛选未分组的数据。
下面是HAVING子句的语法:
```
SELECT column1, aggregate_function(column2)
FROM table_name
WHERE condition
GROUP BY column1
HAVING condition
```
在上面的语法中,HAVING子句必须跟在GROUP BY子句之后,而且它只能使用聚合函数和分组字段进行筛选。
以下是一些使用HAVING子句的示例:
1. 找出销售额大于1000的销售员:
```
SELECT salesman_id, SUM(amount) as total_sales
FROM sales
GROUP BY salesman_id
HAVING SUM(amount) > 1000;
```
2. 找出有两个或以上订单的客户:
```
SELECT customer_id, COUNT(order_id) as total_orders
FROM orders
GROUP BY customer_id
HAVING COUNT(order_id) >= 2;
```
3. 找出平均成绩大于80的学生:
```
SELECT student_name, AVG(score) as average_score
FROM exam_scores
GROUP BY student_name
HAVING AVG(score) > 80;
```
阅读全文