MariaDB/MySQL。在分组中查找具有最大值和最小值的行字段

MariaDB/MySQL. Find row fields with max and min values in a grouping

我有这个问题。 returns每日最低和最高温度:

select  year(DateTimeS),month(DateTimeS),day(DateTimeS),min(Low),max(High) from temperature
where year(DateTimeS) = 2018
group by year(DateTimeS),month(DateTimeS),day(DateTimeS)

我在此查询中缺少两个字段,LowTime 和 MaxTime。我无法弄清楚如何获得最小(低)和最大(高)发生的时间。 (DateTimeS是一个DateTime Field,其余都是十进制)table有分分钟的温度数据是这样的:

+-----------------------+--------+-------+
|      "DateTimeS"      | "High" | "Low" |
+-----------------------+--------+-------+
| "2018-09-07 23:58:00" | "89"   | "87"  |
| "2018-09-07 23:57:00" | "88"   | "85"  |
| "2018-09-07 23:56:00" | "86"   | "82"  |
|        .              |        |       |
|        etc...         |        |       |
+-----------------------+--------+-------+

有什么想法吗?

在 MariaDB 10.3 中,您应该可以使用 window 函数。所以:

select year(DateTimeS), month(DateTimeS), day(DateTimeS),
       min(Low), max(High),
       max(case when seqnum_l = 1 then DateTimeS end) as dateTimeS_at_low,
       max(case when seqnum_h = 1 then DateTimeS end) as dateTimeS_at_high
from (select t.*,
             row_number() over (partition by date(DateTimeS) order by low) as seqnum_l,
             row_number() over (partition by date(DateTimeS) order by high desc) as seqnum_h
      from temperature t
     ) t
where year(DateTimeS) = 2018
group by year(DateTimeS), month(DateTimeS), day(DateTimeS);