Select 来自 table 特定日期的最高温度

Select from table max temperature on specific date

我有一个 table 具有以下数据

Temperature    DateTimeValue         WarnCrit
29.1        2020-06-22 10:08:30         0
29.2        2020-06-22 09:38:28         0
29.2        2020-06-22 09:08:26         0
28.9        2020-06-22 08:38:26         0
28.7        2020-06-22 08:08:24         0
28.7        2020-06-22 07:38:22         0
29.2        2020-06-22 07:08:21         0
29.8        2020-06-22 06:38:20         0
29.9        2020-06-22 06:08:18         0

我想做一个 select 来查找特定日期的最高、最低、平均温度,所以我使用以下内容:

SELECT max(Temperature) as maxtemp
     , min(Temperature) as mintemp
     , avg(Temperature) as avtemp 
  FROM TempHistory 
 WHERE date(DateTimeValue)='2020-06-22'

这项工作是正确的,但我也想知道这个温度发生的具体时间。所以我将其更改为:

SELECT * 
  from TempHistory 
 where DateTimeValue = '2020-06-22' 
   and Temperature = (select max(Temperature) from TempHistory)

这个return没什么。

如果没有关系(或者你不关心它们),你可以这样写:

select t.* 
from TempHistory t
where t.DateTimeValue = (
    select t1.DateTimeValue
    from TempHistory t1
    where t1.DateTimeValue >= '2020-06-22' and t1.DateTimeValue < '2020-06-23'
    order by Temperature desc
    limit 1
)

理由:

  • 你的日期有时间部分,所以你需要一个不等式过滤器

  • 使用子查询更简单 returns 温度最高的日期而不是温度本身(因此,您不需要在外部过滤日期查询)

如果您想要当天温度最低的行,只需从 order by 子句中删除 desc

您可以使用 window 函数,特别是 first_value():

SELECT DISTINCT max(Temperature) OVER () as maxtemp,
       min(Temperature) OVER () as mintemp,
       avg(Temperature) OVER () as avtemp,
       FIRST_VALUE(DateTimeValue) OVER (ORDER BY Temperature ASC) as dt_at_min,
       FIRST_VALUE(DateTimeValue) OVER (ORDER BY Temperature DESC) as dt_at_max
FROM TempHistory 
WHERE DateTimeValue >= '2020-06-22' AND
      DateTimeValue < '2020-06-23';

不幸的是,MySQL(通常 SQL)没有“第一个”或“最后一个”聚合函数。但是,这很相似。

另请注意 WHERE 的更改。这允许查询使用 DateTimeValue 上的索引——如果一个索引可用的话。