0

The following query grabs the temperature, outside temperature, ph and total suspended solids from my aquarium database and displays it in 1 table shown below. each of the values is stored in its own table and is being logged every minute.

I would like to change the query below to be able to get the average value for each hour instead of displaying the value stored in the database at x hour:00:00.

Please help

SELECT DATE_FORMAT(timeTable.minuteTime, '%Y-%m-%d %k:%i') time,
oT2.temperature temperature,
T2.temperature temp,
S2.solids solids,
P2.Ph Ph
FROM
(
    SELECT minuteTime.minuteTime minuteTime,
    ( SELECT MAX(time) FROM outside_temperature WHERE time <= minuteTime.minuteTime AND time >= NOW() - INTERVAL 1 DAY) otempTime, 
    ( SELECT MAX(time) FROM temperature1 WHERE time <= minuteTime.minuteTime AND time >= NOW() - INTERVAL 1 DAY) tempTime, 
    ( SELECT MAX(time) FROM Ph WHERE time <= minuteTime.minuteTime AND time >= NOW() - INTERVAL 1 DAY) phTime,  
    ( SELECT MAX(time) FROM solids WHERE time <= minuteTime.minuteTime AND time >= NOW() - INTERVAL 1 DAY) solidsTime

    FROM  
    (
        SELECT DATE(time) + INTERVAL (HOUR(time) DIV 2 * 2) HOUR minuteTime
        FROM Ph
        WHERE time >= NOW() - INTERVAL 1 DAY AND time <= NOW()
        UNION SELECT DATE(time) + INTERVAL (HOUR(time) DIV 2 * 2) HOUR
        FROM solids
        WHERE time >= NOW() - INTERVAL 1 DAY AND time <= NOW()
        UNION SELECT DATE(time) + INTERVAL (HOUR(time) DIV 2 * 2) HOUR
        FROM outside_temperature
        WHERE time >= NOW() - INTERVAL 1 DAY AND time <= NOW()
        UNION SELECT DATE(time) + INTERVAL (HOUR(time) DIV 2 * 2) HOUR
        FROM temperature1
        WHERE time >= NOW() - INTERVAL 1 DAY AND time <= NOW()
        GROUP BY 1
    ) minuteTime
) timeTable
LEFT JOIN outside_temperature oT2 ON oT2.time = timeTable.otempTime
LEFT JOIN temperature1 T2 ON T2.time = timeTable.tempTime
LEFT JOIN solids S2 ON S2.time = timeTable.solidsTime
LEFT JOIN Ph P2 ON P2.time = timeTable.phTime
ORDER BY minuteTime ASC

This is the result of the query

2013-04-03 22:00    27.12   26.06   139 7.54
2013-04-04 0:00     27.06   26      142 7.54
2013-04-04 2:00     26.94   26      142 7.5
2013-04-04 4:00     26.87   25.94   142 7.5
2013-04-04 6:00     26.75   25.87   141 7.58
2013-04-04 8:00     26.87   25.87   141 7.58
2013-04-04 10:00    26.87   25.87   141 7.58
2013-04-04 12:00    26.87   25.87   141 7.58
2013-04-04 14:00    26.69   25.87   144 7.54
2013-04-04 16:00    26.56   25.81   144 7.58
2013-04-04 18:00    26.5    25.75   144 7.61
2013-04-04 20:00    26.81   25.75   144 7.43
4

1 回答 1

0

利用

SELECT DATE_FORMAT(timeTable.minuteTime, '%Y-%m-%d %k:%i') time,
AVG(oT2.temperature) temperature,
AVG(T2.temperature) temp,
AVG(S2.solids) solids,
AVG(P2.Ph) Ph
......./*YOUR QUERY
--AT THE LAST
GROUP BY DATE_FORMAT(timeTable.minuteTime, '%Y-%m-%d %k:%i') 
于 2013-04-04T11:36:19.260 回答