PostgreSQL With语法例子

本文通过实例演示了如何使用PostgreSQL的聚合函数进行数据分组和统计,特别关注于找出每组中出现频率最高的值及其计数。通过子查询和WITH语句,展示了SQL查询的灵活性和效率。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天看到网上的例子,可以参考PostgreSQL聚合例子,如下:

postgres=# create table test(id int, info text);  
CREATE TABLE  
postgres=# insert into test values (1,'test1');  
INSERT 0 1  
postgres=# insert into test values (1,'test1');  
INSERT 0 1  
postgres=# insert into test values (1,'test2');  
INSERT 0 1  
postgres=# insert into test values (1,'test3');  
INSERT 0 1  
postgres=# insert into test values (2,'test1');  
INSERT 0 1  
postgres=# insert into test values (2,'test1');  
INSERT 0 1  
postgres=# insert into test values (2,'test1');  
INSERT 0 1  
postgres=# insert into test values (3,'test4');  
INSERT 0 1  
postgres=# insert into test values (3,'test4');  
INSERT 0 1  
postgres=# insert into test values (3,'test4');  
INSERT 0 1  
postgres=# insert into test values (3,'test4');  
INSERT 0 1  
postgres=# insert into test values (3,'test4');  
INSERT 0 1  
postgres=# select * from test;  
 id | info    
----+-------  
  1 | test1  
  1 | test1  
  1 | test2  
  1 | test3  
  2 | test1  
  2 | test1  
  2 | test1  
  3 | test4  
  3 | test4  
  3 | test4  
  3 | test4  
  3 | test4  
(12 rows)  

根据id分组并统计每个分组的info列出现频率最高的值以及其出现的次数。

可以使用 subquery解决。

sde=# select id,info,cnt from
sde-# (select id,info,cnt,row_number() over(partition by id order by cnt desc) as rn from
sde(#  (select id,info,count(*) cnt from test group by id,info) t) t
sde-#  where t.rn=1;
 id | info  | cnt
----+-------+-----
  1 | test1 |   2
  2 | test1 |   3
  3 | test4 |   5
(3 行记录)

如果使用with语法,结构会更清晰,如下所示:

sde=# with t1 as
sde-# (
sde(# select id,info,count(*) cnt from test group by id,info
sde(# ),
sde-# t2 as
sde-# (
sde(# select id,info,cnt,row_number() over (partition by id order by cnt desc) as rn from t1
sde(# ),
sde-# t3 as
sde-# (
sde(# select id,info,cnt from t2 where rn=1
sde(# )
sde-#
sde-# select * from t3;
 id | info  | cnt
----+-------+-----
  1 | test1 |   2
  2 | test1 |   3
  3 | test4 |   5
(3 行记录)

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值