【问题标题】:Select from table max temperature on specific date从表中选择特定日期的最高温度
【发布时间】:2020-10-12 00:44:50
【问题描述】:

我有一个包含以下数据的表格

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

这什么也不返回。

【问题讨论】:

  • 子查询也需要日期。
  • 我试了一下,还是没有返回,谢谢你的格式化!

标签: mysql sql greatest-n-per-group


【解决方案1】:

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

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
)

理由:

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

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

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

【讨论】:

  • 我试试这个,我得到了这个错误 MySQL 说:文档 #1051 - 未知表 'database.t' 另外我想问一下,为什么你不使用 = 在哪里?其中日期(t1.DateTimeValue)='2020-06-21'?
  • @GKal: 是的,date(t1.DateTimeValue) = '2020-06-21' 是可能的,但使用半开间隔进行过滤比使用日期函数更有效。
  • @GKal 因为函数不能使用索引
  • @GMB 请问你的回答和下面的有什么区别? select * from TempHistory t1 where t1.DateTimeValue >= '2020-06-22' and t1.DateTimeValue
【解决方案2】:

你可以使用窗口函数,尤其是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)没有“first”或“last”聚合函数。但是,这非常相似。

还要注意对WHERE 的更改。这允许查询使用DateTimeValue 上的索引——如果可用的话。

【讨论】:

  • 哇!!!我没想到会这样!非常感谢,我会立即尝试,我会阅读不同的内容,但是可以尝试解释一下吗?再次感谢您!
  • 另外,我可以使用以下方法获取月份和年份的值吗? WHERE DateTimeValue &gt;= '2020-06' AND DateTimeValue &lt; '2020-07';
  • 我建议使用完整日期:'2020-06-01''202-07-01' 作为常量。我认为 MySQL 支持部分日期,但没有必要。
  • 我使用了你的解决方案,但出现以下错误。错误“静态分析:分析过程中发现 42 个错误。之前发现了一个别名。(位置 44 的“maxtemp”附近)应有别名。(位置 43 的“”附近)意外的令牌。(位置的“maxtemp”附近44) 意外标记。(靠近位置 51 的“,”)无法识别的关键字。(靠近位置 61 的“min”)意外标记。(靠近位置 64 的“(”)意外标记。(靠近位置 65 的“温度”) "
  • @GKal 。 . .我不知道您使用的是什么工具,但无论如何代码中绝对没有 42 个错误。我可能猜到该工具无法识别窗口函数。
猜你喜欢
  • 2016-01-22
  • 1970-01-01
  • 2015-01-13
  • 1970-01-01
  • 2011-08-26
  • 2019-02-09
  • 1970-01-01
  • 2014-11-29
  • 1970-01-01
相关资源
最近更新 更多