Postgresql 按日期和特定 ID 选择前 x 行
Posted
技术标签:
【中文标题】Postgresql 按日期和特定 ID 选择前 x 行【英文标题】:Posgresql SELECT first x rows by date and specific id 【发布时间】:2020-08-31 04:38:07 【问题描述】:我有这张桌子:
+----+--------+--------+-----------+----------------------------+
| id | type | amount | dealer_id | date |
+----+--------+--------+-----------+----------------------------+
| 12 | sub_s | 29.00 | 502 | 2020-05-21 10:05:41.725+02 |
| 11 | sub_pe | 79.00 | 501 | 2020-05-20 09:05:41.725+02 |
| 10 | sub_pe | 79.00 | 501 | 2020-05-19 09:05:41.725+02 |
| 9 | sub_pe | 79.00 | 501 | 2020-05-18 09:05:41.725+02 |
| 8 | sub_pe | 79.00 | 501 | 2020-05-17 09:05:41.725+02 |
| 7 | sub_pe | 79.00 | 501 | 2020-05-16 09:05:41.725+02 |
| 6 | sub_pe | 79.00 | 501 | 2020-05-15 09:05:41.725+02 |
| 5 | sub_pe | 79.00 | 501 | 2020-05-14 09:05:41.725+02 |
| 4 | sub_pe | 79.00 | 501 | 2020-05-13 09:05:41.725+02 |
| 1 | sub_pe | 79.00 | 501 | 2020-05-12 09:05:41.725+02 |
+----+--------+--------+-----------+----------------------------+
如何只为每个dealer_id 选择前6 行(按日期ASC 排序)?
结果如下:
+----+--------+--------+-----------+----------------------------+
| id | type | amount | dealer_id | date |
+----+--------+--------+-----------+----------------------------+
| 12 | sub_s | 29.00 | 502 | 2020-05-21 10:05:41.725+02 |
| 8 | sub_pe | 79.00 | 501 | 2020-05-17 09:05:41.725+02 |
| 7 | sub_pe | 79.00 | 501 | 2020-05-16 09:05:41.725+02 |
| 6 | sub_pe | 79.00 | 501 | 2020-05-15 09:05:41.725+02 |
| 5 | sub_pe | 79.00 | 501 | 2020-05-14 09:05:41.725+02 |
| 4 | sub_pe | 79.00 | 501 | 2020-05-13 09:05:41.725+02 |
| 1 | sub_pe | 79.00 | 501 | 2020-05-12 09:05:41.725+02 |
+----+--------+--------+-----------+----------------------------+
【问题讨论】:
【参考方案1】:带有ROW_NUMBER()
窗口功能:
select t.id, t.type, t.amount, t.dealer_id, t.date
from (
select * ,
row_number() over (partition by dealer_id order by date) rn
from tablename
) t
where t.rn <= 6
【讨论】:
以上是关于Postgresql 按日期和特定 ID 选择前 x 行的主要内容,如果未能解决你的问题,请参考以下文章
如何编辑我的 postgreSQL 查询以按日期选择几列的最新行
MySQL:按日期选择前 5 个和后 5 个条目,1 个查询,没有子查询