📜  SQL-具有子句

📅  最后修改于: 2020-12-29 04:40:48             🧑  作者: Mango


HAVING子句使您可以指定条件,以过滤出哪些组结果出现在结果中。

WHERE子句将条件放在所选列上,而HAVING子句将条件放在GROUP BY子句创建的组上。

句法

以下代码块显示了HAVING子句在查询中的位置。

SELECT
FROM
WHERE
GROUP BY
HAVING
ORDER BY

HAVING子句必须在查询中的GROUP BY子句之后,并且还必须在ORDER BY子句(如果使用)之前。以下代码块具有SELECT语句的语法,包括HAVING子句-

SELECT column1, column2
FROM table1, table2
WHERE [ conditions ]
GROUP BY column1, column2
HAVING [ conditions ]
ORDER BY column1, column2

考虑具有以下记录的CUSTOMERS表。

+----+----------+-----+-----------+----------+
| ID | NAME     | AGE | ADDRESS   | SALARY   |
+----+----------+-----+-----------+----------+
|  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
|  2 | Khilan   |  25 | Delhi     |  1500.00 |
|  3 | kaushik  |  23 | Kota      |  2000.00 |
|  4 | Chaitali |  25 | Mumbai    |  6500.00 |
|  5 | Hardik   |  27 | Bhopal    |  8500.00 |
|  6 | Komal    |  22 | MP        |  4500.00 |
|  7 | Muffy    |  24 | Indore    | 10000.00 |
+----+----------+-----+-----------+----------+

以下是一个示例,该示例将显示一个类似的年龄计数(大于或等于2)的记录。

SQL > SELECT ID, NAME, AGE, ADDRESS, SALARY
FROM CUSTOMERS
GROUP BY age
HAVING COUNT(age) >= 2;

这将产生以下结果-

+----+--------+-----+---------+---------+
| ID | NAME   | AGE | ADDRESS | SALARY  |
+----+--------+-----+---------+---------+
|  2 | Khilan |  25 | Delhi   | 1500.00 |
+----+--------+-----+---------+---------+