从数据库中的每个用户获取最后一个条目

Get last entry from each user in database

我有一个 Postgresql 数据库,但我无法正确查询,尽管这似乎是一个常见问题。

我的 table 看起来像这样:

CREATE TABLE orders (
   account_id   INTEGER,
   order_id     INTEGER,
   ts           TIMESTAMP DEFAULT NOW()
)

每次有新订单,我都会用它来 link account_idorder_id

现在我的问题是我想获得一个包含每个帐户的最后订单(通过查看 ts)的列表。

例如,如果我的数据是:

account_id    order_id            ts
         5         178        July 1
         5         129        July 6
         4         190        July 1
         4         181        July 9
         3         348        July 1
         3         578        July 4
         3         198        July 1
         3         270       July 12

然后我想查询 return 每个帐户的最后一行:

account_id    order_id            ts
         5         129        July 6
         4         181        July 9
         3         270       July 12

我试过 GROUP BY account_id,我可以用它来获取每个帐户的 MAX(ts),但是我无法获取关联的 order_id。我也尝试过子查询,但我似乎做错了。

谢谢!

row_number() window 函数可以帮助:

select account_id, order_id, ts
  from (select account_id, order_id, ts,
               row_number() over(partition by account_id order by ts desc) as rn
          from tbl) t
 where rn = 1
select distinct on (account_id) *
from orders
order by account_id, ts desc

https://www.postgresql.org/docs/current/static/sql-select.html#SQL-DISTINCT:

SELECT DISTINCT ON ( expression [, ...] ) keeps only the first row of each set of rows where the given expressions evaluate to equal. The DISTINCT ON expressions are interpreted using the same rules as for ORDER BY (see above). Note that the "first row" of each set is unpredictable unless ORDER BY is used to ensure that the desired row appears first.