SQL select HIGHEST 时间戳为 LOWEST 的记录

SQL select the record whose HIGHEST timestamp is the LOWEST

我有一个包含重复名称和时间戳的数据库 我想检索时间戳按名称分组最低的记录。

table : people
+------------+-------------+
|  Name      |  Timestamp  |
+------------+-------------+
|   name1    |   0         |
|   name1    |   5         |
|   name2    |   2         |
|   name3    |   3         |
|   name2    |   1         |
+--------------------------+

对于处于这种状态的数据库,查询应该 return "name2, 2" 因为 name2 的最大值是所有组最大值中的最小值。

我一直在思考这个问题,因为我知道我做过类似的查询,但我的 SQL 技能太生疏了。

感谢所有花时间提供帮助的人:)

看来你想要最大时间戳最小的名称:如果是这样,你可以使用聚合和限制:

select name
from people
group by name
order by max(timestamp)
limit 1

如果你想允许可能的联系:

select name
from (
    select name, rank() over(order by max(timestamp)) rn
    from people
    group by name
) t
where rn = 1

另一方面,如果你想要整个记录,我建议在 Postgres 中使用 distinct on

select *
from (
    select distinct on (name) *
    from people
    order by name, timestamp desc
) t
order by timestamp
limit 1