SQL Having子句
HAVING子句允許您指定過濾器的條件,分組結果會出現在最終結果。
WHERE子句所選列的條件,而由GROUP BY子句條件創建分組的HAVING子句。
語法
下面是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 |
+----+----------+-----+-----------+----------+
下面是示例,這將顯示記錄age大於或等於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 |
+----+--------+-----+---------+---------+