【问题标题】:SQL select the record whose HIGHEST timestamp is the LOWESTSQL选择HIGHEST时间戳为LOWEST的记录
【发布时间】:2020-12-19 02:42:49
【问题描述】:

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

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

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

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

感谢任何花时间提供帮助的人:)

【问题讨论】:

    标签: sql postgresql max sql-order-by greatest-n-per-group


    【解决方案1】:

    您似乎想要最大时间戳最低的名称:如果是这样,您可以使用聚合和限制:

    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
    

    【讨论】:

    • 看起来聚合和限制是要走的路,我正在努力,但你肯定帮了很多忙,非常感谢
    • 仍然不知道如何在不使用其他查询的情况下提取整条记录
    • @NachoR:我明白你的意思。我编辑了答案中的最后一个查询,它应该做你想做的事。
    • 这正是我想要的,现在我可以执行更新记录所需的所有查询。希望这也对其他人有所帮助:)
    猜你喜欢
    • 1970-01-01
    • 2017-07-10
    • 1970-01-01
    • 2023-02-11
    • 2012-02-02
    • 2017-07-14
    • 1970-01-01
    • 2014-02-06
    • 2014-01-23
    相关资源
    最近更新 更多