Postgres select 基于时间戳不同

Postgres select distinct based on timestamp

我有一个包含两列 a 和 b 的 table,其中 a 是 ID,b 是时间戳。 我需要 select 所有不同的 a,但我只关心每个 ID 的最新行。

即我需要一种 select 以 b 值为条件的不同 a 的方法。

有没有办法在 postgres 中使用 DISTINCT ON 来做到这一点?

干杯

就像@a_horse_with_no_name建议的那样,解决方案是

SELECT DISTINCT ON (a) a, b FROM the_table ORDER BY a, b DESC

正如the manual所说,

Note that the "first row" of a set is unpredictable unless the query is sorted on enough columns to guarantee a unique ordering of the rows arriving at the DISTINCT filter. (DISTINCT ON processing occurs after ORDER BY sorting.)

正如赞成的答案所发布的那样,SELECT DISTINCT ON (a) a, b FROM the_table ORDER BY a, b DESC 适用于 Postgre 12。但是,我发布这个答案是为了强调几个要点:

  1. 结果将按a列排序;不是 b 列。
  2. 在每个结果行中,将选择 b 列的最新(最大值)。
  3. 万一有人想获取整个结果集上 b 列的最新值,在 sql 中,我们可以 运行 : SELECT MAX(b) from (SELECT DISTINCT ON (a) a, b FROM the_table ORDER BY a, b DESC).