如何为每个ID选择前2个值

时间:2019-10-22 07:40:06

标签: sql postgresql greatest-n-per-group

我有一个带有值的表

id  sales     date
1   5   "2015-01-04"
1   3   "2015-01-03"
1   1   "2015-01-01"
1   1   "2015-01-01"
2   7   "2015-01-05"
2   6   "2015-01-04"
2   4   "2015-01-03"
3   11  "2015-01-08"
3   10  "2015-01-07"
3   9   "2015-01-06"
3   8   "2015-01-05"

我想要选择每个id的前两个值,如期望的输出所示。

所需的输出:

id   sales     date
 1    5        "2015-01-04"
 1    3        "2015-01-03"
 2    7        "2015-01-05"
 2    6        "2015-01-04"
 3    11       "2015-01-08"
 3    10       "2015-01-07"

我的尝试

有人可以帮我这个忙吗?预先谢谢你!

select transactions.salesperson_id, transactions.id, transactions.date
from transactions
ORDER BY transactions.salesperson_id ASC, transactions.date DESC;

2 个答案:

答案 0 :(得分:2)

这可以使用窗口功能来完成:

select id, sales, "date"
from (
  select id, sales, "date", 
         dense_rank() over (partition by id order by "date" desc) as rnk
  from transactions
) t
where rnk <= 2;

如果同一日期有多行,则对于同一ID可能会返回多于两行。如果您不想这样做,请使用row_number()代替dense_rank()

答案 1 :(得分:0)

row_number()将得到您想要的。

select * from 
    (select row_number() over (partition by id order by date) as rn, sales, date from transactions) t1
where t1.rn <= 2