HAVING子句使您可以指定條件,以過濾哪些組結(jié)果出現(xiàn)在最終結(jié)果中。
WHERE子句在所選列上放置條件,而HAVING子句在GROUP BY子句創(chuàng)建的組上放置條件。
以下是HAVING子句在SELECT查詢中的位置。
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
考慮帶有以下記錄的COMPANY表。
ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 1 Paul 32 California 20000.0 2 Allen 25 Texas 15000.0 3 Teddy 23 Norway 20000.0 4 Mark 25 Rich-Mond 65000.0 5 David 27 Texas 85000.0 6 Kim 22 South-Hall 45000.0 7 James 24 Houston 10000.0 8 Paul 24 Houston 20000.0 9 James 44 Norway 5000.0 10 James 45 Texas 5000.0
以下是示例,它將顯示名稱計數(shù)小于2的記錄。
sqlite > SELECT * FROM COMPANY GROUP BY name HAVING count(name) < 2;
這將產(chǎn)生以下結(jié)果。
ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 2 Allen 25 Texas 15000 5 David 27 Texas 85000 6 Kim 22 South-Hall 45000 4 Mark 25 Rich-Mond 65000 3 Teddy 23 Norway 20000
下面是示例,它將顯示名稱計數(shù)大于2的記錄。
sqlite > SELECT * FROM COMPANY GROUP BY name HAVING count(name) > 2;
這將產(chǎn)生以下結(jié)果。
ID NAME AGE ADDRESS SALARY ---------- ---------- ---------- ---------- ---------- 10 James 45 Texas 5000