【问题标题】:select the SECOND highest value for each group in mySQL 5为 mySQL 5 中的每个组选择第二个最高值
【发布时间】:2021-02-13 00:25:08
【问题描述】:

此代码获取每个 ID 的 ID 和最新时间​​戳

select id, max(start_time) as start1, max(end_time) as end1 from table group by id

如何获得第二高的时间戳作为 start2 和 end2?

【问题讨论】:

  • 样本数据和期望的结果会有所帮助。例如,对于给定的 id,行是否按开始/结束时间平铺?

标签: mysql sql subquery max min


【解决方案1】:

一个选项使用相关子查询:

select 
    id, 
    max(start_time) as start1, 
    max(end_time) as end1,
    (
        select t1.start_time
        from mytable t1
        where t1.id = t.id
        order by t1.start_time desc
        limit 1, 1
    ) start2,
    (
        select t1.end_time
        from mytable t1
        where t1.id = t.id
        order by t1.end_time desc
        limit 1, 1
    ) end2
from mytable t
group by id

【讨论】:

  • 如果我想将它扩展到第 n 高怎么办?
  • @ignacio.natas:只需将第一个参数更改为limitlimit 2, 1 给你第三高,依此类推。
猜你喜欢
  • 1970-01-01
  • 2021-07-23
  • 1970-01-01
  • 1970-01-01
  • 2021-04-01
  • 2021-12-04
  • 1970-01-01
  • 1970-01-01
  • 2019-07-01
相关资源
最近更新 更多