GaussDB having 的用法

发布于:2025-08-03 ⋅ 阅读:(7) ⋅ 点赞:(0)

1 having 的作用

      having 子句使你能够指定过滤条件,从而控制查询结果中哪些组可以出现在最终结果里面。where 子句对被选择的列施加条件,而 having 子句则对 group by 子句所产生的组施加条件。

2 having 语法

下面可以看到 having 子句在 select 查询中的位置:
select
from
where
group by
having
order by
在 select 查询中,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;

3 having 实例

考虑 customers 表,表中的记录如下所示:
csdn=> select * from customers;
 id | name |     addr     | city |  zip   | province | age
----+------+--------------+------+--------+----------+-----
  1 | 张三 | 北京路27号   | 上海 | 200000 | 上海市   |
  2 | 李四 | 南京路12号   | 杭州 | 310000 | 浙江市   |
  3 | 王五 | 花城大道17号 | 广州 | 510000 | 广州省   |
  4 | 马六 | 江夏路19号   | 武汉 | 430000 | 湖北省   |
  5 | 赵七 | 西二旗12号   | 北京 | 100000 | 北京市   |
  7 | 老六 | 西二旗12号   | 北京 | 100000 | 北京市   |
(6 rows)

csdn=>
csdn=>
csdn=>
下面是一个有关 having 子句使用的实例,该实例将会筛选出"城市"列的内容出
现次数大于或等于 2 的所有记录。

示代:
select * from customers
where city in (
select city from customers
group by city
having count(1)>1
)

结果:

注:

上面的代码用了一个子查询,主要是因为在 GaussDB中group by 分组后,在select 后面显示的列里面只能显示分组的列,比如我们这里对城市分组了,那么子查询里面就只能显示城市列,如果要显示其他列,比如要还要显示"省份"

select city,province from customers
group by city
having count(1)>1;

结果:

ERROR:  Column "customers.province" must appear in the GROUP BY clause or be used in an aggregate function.
LINE 1: select city,province from customers
                    ^

所以我们将筛选出来符合条件的内容,通过子查询再传递给外面的主查询。主查询就可以不受 group by 的约束显示你想显示的内容了。


网站公告

今日签到

点亮在社区的每一天
去签到