复合主键上的PostgreSQL SELECT DISTINCT

问题描述 投票:1回答:1

我有这种结构的表:

Column    |  Type |
id        | int   | 
version   | int   |
status_id | int   |  // can be 1 active, 2 suspended, 3 removed
update    | Timestamp |
position  | Geometry  |

Indexes:
"PK_poi" PRIMARY KEY, btree (id, version)

所以这是我的表结构,基本上会在Location发生,我会创建它,然后会发生其他事情,我会用新版本更新事件。

所以数据就像

 id         |  version  | status_id |  update              | position
 1          |  1        |   1       |  2018-09-17 10:52:48 | x,y 
 2          |  1        |   1       |  2018-09-17 10:52:48 | x,y
 2          |  2        |   1       |  2018-09-17 11:02:48 | x,y
 2          |  3        |   2       |  2018-09-17 11:22:48 | x,y
 1          |  2        |   2       |  2018-09-17 11:52:48 | x,y
 2          |  4        |   1       |  2018-09-17 12:52:48 | x,y
 1          |  3        |   3       |  2018-09-17 12:52:48 | x,y
 2          |  5        |   3       |  2018-09-17 13:52:48 | x,y
 3          |  1        |   1       |  2018-09-17 14:52:48 | x,y
 3          |  2        |   1       |  2018-09-17 14:52:48 | x,y
 4          |  1        |   1       |  2018-09-17 16:52:48 | x,y
 4          |  2        |   1       |  2018-09-17 16:52:48 | x,y

所以我试图做一个distint select,它根据时间戳在指定的时间间隔内返回“最新”版本。但只有“最新”版本没有状态 - 暂停或删除。

因此,如果在17:52我查询数据库,我说在过去一小时内给我最新的事件,我希望:

  id         |  version  | status_id |  update              | position
  4          |  2        |   1       |  2018-09-17 16:52:48 | x,y

但是,如果我说,请给我最近24小时的最新事件,我希望如此

  id         |  version  | status_id |  update              | position
  3          |  2        |   1       |  2018-09-17 14:52:48 | x,y
  4          |  2        |   1       |  2018-09-17 16:52:48 | x,y

由于复合键,我很困惑如何做到这一点。你能指点我应该读什么吗?

先感谢您

postgresql composite-primary-key
1个回答
1
投票

您需要row_number才能获得每个位置的最新活动。

SELECT *
FROM ( SELECT *, 
              ROW_NUMBER() OVER (PARTITION BY id ORDER BY "update" DESC ) as rn
                                          -- ^^^ create a group for each id
       FROM yourTable           
       WHERE status_id = 1
         -- optional if you want the events in a time range
         AND "update" > current_timestamp - interval '1 day -- filter the last 24 h events
     ) as Q

-- optional if you want all events remove it.
WHERE rn = 1 -- filter the last one of each id because is order by update desc
© www.soinside.com 2019 - 2024. All rights reserved.