简体   繁体   English

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

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

I have a table that looks something like this:我有一个看起来像这样的表:

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

What I would like to do is perform a SELECT combined with a LIMIT X to get X number of records as well as any other records that have the same customer_id我想做的是执行SELECT结合LIMIT X以获得 X 条记录以及具有相同customer_id的任何其他记录

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

customer_id客户ID data数据
1 1 123 123
1 1 456 456
2 2 789 789

I'd like a query that will look at the last customer_id value and return all remaining records that match beyond the LIMIT specified.我想要一个查询,该查询将查看最后一个customer_id值并返回匹配超出指定LIMIT的所有剩余记录。 Is it possible to do this in a single operation?是否有可能在一次操作中做到这一点?

Desired output:所需的 output:

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

In Postgres 13 can use with ties :在 Postgres 13 中可以使用with ties

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

In earlier versions you can use in :在早期版本in ,您可以使用:

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

You can use corelated subquery with count as follows:您可以将相关子查询与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