繁体   English   中英

具有限制的 Postgres 查询选择具有相似标识符的所有记录

[英]Postgres query with limit that selects all records with similar identifier

我有一个看起来像这样的表:

客户ID 数据
1 123
1 456
2 789
2 101
2 121
2 123
3 123
4 456

我想做的是执行SELECT结合LIMIT X以获得 X 条记录以及具有相同customer_id的任何其他记录

查询示例: SELECT customer_id, data FROM table ORDER BY customer_id LIMIT 3; 此查询返回:

客户ID 数据
1 123
1 456
2 789

我想要一个查询,该查询将查看最后一个customer_id值并返回匹配超出指定LIMIT的所有剩余记录。 是否有可能在一次操作中做到这一点?

所需的 output:

客户ID 数据
1 123
1 456
2 789
2 101
2 121
2 123

在 Postgres 13 中可以使用with ties

select t.*
from t
order by customer_id
fetch first 3 rows with ties;

在早期版本in ,您可以使用:

select t.*
from t
where t.customer_id in (select t2.customer_id
                        from t t2
                        order by t2.customer_id
                        limit 3
                       );

您可以将相关子查询与count一起使用,如下所示:

Select t.*
  From t
 Where 3 >= (select count(distinct customer_id)
               From t tt 
              where t.customer_id >= tt.customer_id)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM