[英]Postgres query with limit that selects all records with similar identifier
I have a table that looks something like this:我有一个看起来像这样的表:
customer_id![]() |
data![]() |
---|---|
1 ![]() |
123 ![]() |
1 ![]() |
456 ![]() |
2 ![]() |
789 ![]() |
2 ![]() |
101 ![]() |
2 ![]() |
121 ![]() |
2 ![]() |
123 ![]() |
3 ![]() |
123 ![]() |
4 ![]() |
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![]() |
data![]() |
---|---|
1 ![]() |
123 ![]() |
1 ![]() |
456 ![]() |
2 ![]() |
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![]() |
data![]() |
---|---|
1 ![]() |
123 ![]() |
1 ![]() |
456 ![]() |
2 ![]() |
789 ![]() |
2 ![]() |
101 ![]() |
2 ![]() |
121 ![]() |
2 ![]() |
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.