扫码一下
查看教程更方便
having 子句允许指定条件来过滤将出现在最终结果中的分组结果。
where 子句在所选列上设置条件,而 having 子句则在由 group by 子句创建的分组上设置条件。
下面是 having 子句在 select 查询中的位置:
select
from
where
group by
having
order by
在一个查询中,having 子句必须放在 group by 子句之后,必须放在 order by 子句之前。下面是包含 having 子句的 select 语句的语法:
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
下面示例将显示名称计数小于 2 的所有记录:
sqlite > select * from company group by name having count(name) < 2;
结果如下:
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
下面示例将显示名称计数大于 2 的所有记录:
sqlite > select * from company group by name having count(name) > 2;
结果如下:
id name age address salary
---------- ---------- ---------- ---------- ----------
10 james 45 texas 5000