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

时间:2018-09-27 00:10:45

标签: mysql sql mariadb groupwise-maximum

我有这个查询。返回每日的最低和最高温度:

def max_date_prior_to_year(dates, yr):
     return dates[dates<pd.to_datetime(str(yr)+'-01-01')].max()

我在此查询中缺少两个字段LowTime和MaxTime。我不知道如何获得最小(低)和最大(高)发生的时间。 (DateTimeS是一个DateTime字段,其余为十进制)该表具有逐分钟的温度数据,如下所示:

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)

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

在MariaDB 10.3中,您应该能够使用窗口功能。所以:

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);