English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
The HAVING clause allows us to filter the data of each group after grouping.
The WHERE clause sets conditions on the selected columns, while the HAVING clause sets conditions on the groups created by the GROUP BY clause.
The following is the position of the HAVING clause in the SELECT query:
SELECT FROM WHERE GROUP BY HAVING ORDER BY
HAVING clause must be placed after the GROUP BY clause and before the ORDER BY clause, the following is the basic syntax of the HAVING clause in the SELECT statement:
SELECT column1, column2 FROM table1, table2 WHERE [conditions] GROUP BY column1, column2 HAVING [ conditions ] ORDER BY column1, column2
创建 COMPANY 表(下载 COMPANY SQL 文件 ),数据内容如下:
w3codeboxdb# select * from COMPANY; id | name | age | address | salary ----+-------+-----+-----------+-------- 1 | Paul | 32 | California| 20000 2 | Allen | 25 | Texas | 15000 3 | Teddy | 23 | Norway | 20000 4 | Mark | 25 | Rich-Mond | 65000 5 | David | 27 | Texas | 85000 6 | Kim | 22 | South-Hall| 45000 7 | James | 24 | Houston | 10000 (7 rows)
下面示例将找出根据 NAME 字段值进行分组,并且 name(名称) 字段的计数少于 2 Données :
SELECT NAME FROM COMPANY GROUP BY name HAVING count(name) < 2;
得到以下结果:
name ------- Teddy Paul Mark David Allen Kim James (7 rows)
我们往表里添加几条数据:
INSERT INTO COMPANY VALUES (8, 'Paul', 24, 'Houston', 20000.00); INSERT INTO COMPANY VALUES (9, 'James', 44, 'Norway', 5000.00); INSERT INTO COMPANY VALUES (10, 'James', 45, 'Texas', 5000.00);
此时,COMPANY 表的记录如下:
id | name | age | address | salary ----+-------+-----+--------------+-------- 1 | Paul | 32 | California | 20000 2 | Allen | 25 | Texas | 15000 3 | Teddy | 23 | Norway | 20000 4 | Mark | 25 | Rich-Mond | 65000 5 | David | 27 | Texas | 85000 6 | Kim | 22 | South-Hall | 45000 7 | James | 24 | Houston | 10000 8 | Paul | 24 | Houston | 20000 9 | James | 44 | Norway | 5000 10 | James | 45 | Texas | 5000 (10 rows)
L'exemple suivant trouvera les enregistrements groupés selon la valeur du champ name et dont le nombre de noms est supérieur à 1 Données :
w3codeboxdb-# SELECT NAME FROM COMPANY GROUP BY name HAVING count(name) > 1;
Résultat obtenu comme suit :
name ------- Paul James (2 rows)