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

时间:2021-01-08 17:34:22

标签: sql postgresql

我有一张看起来像这样的桌子:

<头>
customer_id 数据
1 123
1 456
2 789
2 101
2 121
2 123
3 123
4 456

我想做的是将 SELECTLIMIT X 结合使用以获得 X 条记录以及具有相同 customer_id 的任何其他记录

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

<头>
customer_id 数据
1 123
1 456
2 789

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

所需的输出:

<头>
customer_id 数据
1 123
1 456
2 789
2 101
2 121
2 123

2 个答案:

答案 0 :(得分:0)

在 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
                       );

答案 1 :(得分:0)

您可以将相关子查询与 ## stacked barplot, at x% height tt <- table(mtcars$gear, mtcars$vs) bp <- barplot(tt) pt <- sprintf('%.f%%', prop.table(tt, margin = 1) * 100) text(rep(bp, each = nrow(tt)), apply(tt, 2, function(x) head(c(0, cumsum(x)), -1) + x * 0.75), pt, xpd = NA) 一起使用,如下所示:

count
相关问题