小编典典

选择具有最大时间戳的值

sql

我有一张表:

id|val|updated
1 | 31|2012-01-12
1 | 34|2012-01-15
2 | 41|2012-01-15
3 | 44|2012-01-15
4 | 66|2012-01-01

我需要选择具有最大更新值的id和val。因此,对于此表,结果应为:

1| 34| 2012-01-15
2| 41| 2012-01-15
3| 44| 2012-01-15
4| 66| 2012-01-01

阅读 136

收藏
2021-04-19

共1个答案

小编典典

这需要MAX()在与主表连接的子查询中进行汇总。

SELECT
  tbl.id,
  tbl.val,
  tbl.updated
FROM tbl JOIN (
  /* Subquery gets MAX(updated) per id  to JOIN against */
  SELECT 
    id,
    MAX(updated) as updated
  FROM tbl
  GROUP BY id
) t2 ON tbl.id = t2.id AND tbl.updated = t2.updated
2021-04-19