![](/img/trans.png)
[英]MySQL query with 2 SELECTs, UNION and LIMIT - how to count all items?
[英]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.