PostgreSQL由N个组限制 [英] Postgresql limit by N groups
本文介绍了PostgreSQL由N个组限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
create table t (a integer, b text);
insert into t values (1, 'a'), (2, 'a'), (3, 'a'), (10, 'b'), (11, 'b'), (0, 'c');
我需要按 b 列的前两个组进行选择-a,2-b);
I need to limit select by 2 first groups of column b (1 - a, 2 - b);
select * from t order by b;
a | b
----+---
1 | a
2 | a
3 | a
10 | b
11 | b
-- limit here
0 | c
(6 rows)
类似于的b在(从b的限制中选择t顺序中的与众不同的(b)2)
没有子查询。
推荐答案
使用Windows函数,例如density_rank:
you can use windows functions like dense_rank :
select *,dense_rank() over (order by b) group_number from t order by b
所以你可以做:
select * from (
select *,dense_rank() over (order by b) group_number from t order by b
) a where group_number<=2
这篇关于PostgreSQL由N个组限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文