【问题标题】:Select rows from MySQL and grouping use MAX and MIN从 MySQL 中选择行并分组使用 MAX 和 MIN
【发布时间】:2015-06-08 01:13:37
【问题描述】:

我有一个名为“ArchiveTable”的表格:

+---------+-----------------+---------+-------- ---------+--------------+------------------+
|最大温度 |最大临时时间 |最低温度 |最小时间 |小风寒 | minwindchilltime |
+---------+------+----------+---------- ------+--------------+------------------+
| 27.9 | 2015 年 3 月 17 日 16:55 | 25.8 | 2015 年 3 月 17 日 19:00 | 25.8 | 2015 年 3 月 17 日 19:00 |
+---------+------+----------+---------- ------+--------------+------------------+
| 25.7 | 2015 年 3 月 17 日 19:05 | 19.3 | 2015 年 3 月 18 日 9:05 | 19.3 | 2015 年 3 月 18 日 9:05 |
+---------+------+----------+---------- ------+--------------+------------------+
| 23.1 | 2015 年 3 月 18 日 19:05 | 18.7 | 2015 年 3 月 19 日 6:30 | 18.7 | 2015 年 3 月 19 日 6:30 |
+---------+------+----------+---------- ------+--------------+------------------+

我必须选择“maxtemp”的最大值及其对应的“maxtemptime”日期,“mintemp”的最小值及其对应的日期,以及“minwindchill”的最小值及其对应的日期。

我知道如何使用MAX()MIN() 函数获取最大值和最小值,但我无法将这些值与相应的日期相关联。

【问题讨论】:

    标签: mysql sql group-by


    【解决方案1】:

    如果您可以在单独的行中获取值,那么您可以执行以下操作:

    (select a.* from archivetable order by maxtemp limit 1) union
    (select a.* from archivetable order by maxtemp desc limit 1) union
    . . .
    

    否则,如果您可以这样做:

    select atmint.mintemp, atmint.mintempdate,
           atmaxt.maxtemp, atmaxt.maxtempdate,
           atminwc.minwindchill, atminwc.minwindchilldate
    from (select min(mintemp) as mintemp, max(maxtemp) as maxtemp, min(minwindchill) as minwindchill
          from archivetable
         ) a join
         archivetable atmint
         on atmint.mintemp = a.mintemp join
         archivetable atmaxt
         on atmaxt.maxtemp = a.maxtemp join
         archivetable atminwc
         on atminwc.minwindchill = a.minwindchill
    limit 1;
    

    limit 1 是因为多行可能具有相同的值。如果是这样,您可以根据问题的表述方式任意选择其中之一。

    【讨论】:

    • 非常感谢,它成功了,但是limit 1on atminwc.minwindchill = a.minwindchill 之后。
    • @AndresCruz 。 . .那是LIMIT 1 的正确位置。
    【解决方案2】:

    看到这个MySQL Handling of GROUP BY

    如果我理解正确,你应该这样做

    SELECT field1, field2, fieldN, COUNT(field1) AS alias FROM table
      GROUP BY field1
     HAVING maxtemp  = MAX(maxtemp); -- I think this is not correct
    

    虽然我不能 100% 确定该解决方案,但您也可以尝试一下

    SELECT field1, field2, fieldN, COUNT(field1) AS alias FROM table
      GROUP BY field1
     HAVING maxtemp  = (SELECT MAX(maxtemp) FROM table);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-22
      • 2018-07-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-05-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多