MIN MAX的每日DATETIME在相邻列的同一行中

时间:2014-07-19 14:46:45

标签: mysql

寻找我编写的查询方法,以显示MIN&最高温度发生在相邻列中同一行的那一天。

我一直在寻找和尝试一些事情,但我对连接有点迷失,我认为你需要使用它。

当前查询和结果..

SELECT 
    YEAR(tstLocal) AS "YEAR", 
    MONTHNAME(tstLocal) AS "MONTH", 
    DAY(tstLocal) AS "DAY",
    min(tempC) AS "DAILY MIN TEMP", 
    max(tempC) AS "DAILY MAX TEMP",  
    ROUND(AVG(tempC),1) AS "DAILY AVG TEMP"
FROM 
    house.outside1
WHERE 
    YEAR(tstLocal) = '2014' AND MONTH(tstLocal) = '7'
GROUP BY 
    YEAR(tstLocal),
    MONTH(tstLocal),
    DAY(tstLocal);

RESULTS

使用DATETIME显示这些MIN / MAX温度时,我需要做什么?

1 个答案:

答案 0 :(得分:2)

由于您已使用group by,因此group_concat() / substring_index()技巧可行:

SELECT YEAR(tstLocal) AS "YEAR", MONTHNAME(tstLocal) AS "MONTH", DAY(tstLocal) AS "DAY",
       min(tempC) AS "DAILY MIN TEMP", max(tempC) AS "DAILY MAX TEMP",
       ROUND(AVG(tempC),1) AS "DAILY AVG TEMP",
       substring_index(group_concat(tstlocal order by tempC asc), ',', 1) as min_datetime,
       substring_index(group_concat(tstlocal order by tempC desc), ',', 1) as max_datetime
FROM house.outside1
WHERE  YEAR(tstLocal) = '2014' AND MONTH(tstLocal) = '7'
GROUP BY YEAR(tstLocal), MONTH(tstLocal),  DAY(tstLocal);