SQLite HAVING子句

SQLite HAVING子句用於指定過濾分組的結果,並作爲最終查詢結果的條件。 WHERE子句將條件放在選定的列上,而HAVING子句指定的條件是由GROUP BY子句創建的列分組上(使用HAVING子句條件一定要作用在由GROUP BY子句指定列上)。

SELECT查詢中HAVING子句的位置:

SELECT  
FROM  
WHERE  
GROUP BY  
HAVING  
ORDER BY

語法

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

下面舉個例子來演示如何使用HAVING子句。假設有一個名爲student的表,並具有以下數據:

sqlite> select * from student;
1|Maxsu|27|Shengzhen|20000.0
2|Minsu|25|Beijing|15000.0
3|Avgsu|23|Shanghai|2000.0
4|Linsu|25|Guangzhou|65000.0
5|Sqlsu|26|Haikou|25000.0
6|Javasu|21|Shengzhen|18000.0
7|Linsu|27|Haikou|10000.0
8|Minsu|23|Guangzhou|5000.0
9|Maxsu|23|Shenzhen|9000.0
sqlite>

示例1:

下面查詢name的數量小於2的所有記錄,在查詢之前,先來查詢看看每個名字的數量 -

-- 名字的數量
SELECT name, count(name) as total_number FROM student GROUP BY name;

-- `name`的數量小於`2`的所有記錄
SELECT name, count(name) as total_number FROM student GROUP BY NAME HAVING COUNT(NAME) < 2;

執行上面語句,得到結果如下 -

-- 所有記錄
sqlite> select * from student;
1|Maxsu|27|Shengzhen|20000.0
2|Minsu|25|Beijing|15000.0
3|Avgsu|23|Shanghai|2000.0
4|Linsu|25|Guangzhou|65000.0
5|Sqlsu|26|Haikou|25000.0
6|Javasu|21|Shengzhen|18000.0
7|Linsu|27|Haikou|10000.0
8|Minsu|23|Guangzhou|5000.0
9|Maxsu|23|Shenzhen|9000.0
sqlite>
sqlite> 
-- 每個名字的數量
sqlite> SELECT name, count(name) as total_number FROM student GROUP BY name;
Avgsu|1
Javasu|1
Linsu|2
Maxsu|2
Minsu|2
Sqlsu|1
-- 查詢數量小於2的名字
sqlite> SELECT name, count(name) as total_number FROM student GROUP BY NAME HAVING total_number < 2;
Avgsu|1
Javasu|1
Sqlsu|1
sqlite>

示例2:

下面查詢address的數量大於等於2的所有記錄,在查詢之前,先來查詢看看每個地址的數量 -

sqlite> SELECT address, count(address) as total_number FROM student GROUP BY address ;
Beijing|1
Guangzhou|2
Haikou|2
Shanghai|1
Shengzhen|2
Shenzhen|1
sqlite> SELECT address, count(address) as total_number FROM student GROUP BY address HAVING total_number >= 2;
Guangzhou|2
Haikou|2
Shengzhen|2
sqlite>