SQL: Using having to implement group filtering

SQL: Using having to implement group filtering


foreword

When many friends are performing database retrieval, they will encounter situations that require group filtering

For example: Now the operation wants to check the average posts and replies of each school user, and find the low-activity schools for key operations. Please select the schools with an average posting number of less than 5 or the average number of replies less than 20 schools.

This article will analyze this example, mainly introducing the usage of the having function

Example link: SQL19 group filtering exercises


1. Introduction to having

Usage: When the result of the aggregation function is used as the filter condition, you cannot use where, but use the having syntax and use it with renaming

For more information, please refer to: GROUP BY and HAVING Usage Introduction
Database Query Statement – ​​HAVING Usage

2. Usage analysis

//数据库表结构
id	device_id	gender	age	university	gpa	active_days_within_30 question_cnt answer_cnt
1	2138	male	21	北京大学	3.4	7	2	12
2	3214	male   null 复旦大学 4.0	15	5	25
3	6543	female	20	北京大学	3.2	12	3	30
4	2315	female	23	浙江大学	3.6	5	1	2
5	5432	male	25	山东大学	3.8	20	15	70
6	2131	male	28	山东大学	3.3	15	7	13
7	4321	female	26	复旦大学	3.6	9	6	52
//搜索语句
select 
	university,
	avg(question_cnt) as avg_question_cnt,
	avg(answer_cnt) as avg_answer_cnt
from user_profile
group by university
having avg_question_cnt < 5 or avg_answer_cnt < 20

Guess you like

Origin blog.csdn.net/qq_46119575/article/details/129827540