![](/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.