- SQLite快速入门
- SQLite是什么?
- SQLite历史
- SQLite特性/为什么要使用SQLite?
- SQLite优点和缺点
- SQLite安装
- SQLite命令大全
- SQLite语法大全
- SQLite数据类型
- SQLite运算符
- SQLite表达式
- 数据库和表
- CURD操作
- 子句和条件
- 连接操作
- SQLite时间日期
- 聚合函数
- SQLite触发器
- SQLite主键
- SQLite导出导入
- SQLite连接程序
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>
关注微信小程序
扫描二维码
程序员编程王