2013-04-04 265 views
0

以下查詢從我的水族館數據庫中獲取溫度,外部溫度,pH和總懸浮固體,並將其顯示在下表所示的1個表格中。每個值都存儲在它自己的表中,並且每分鐘記錄一次。mysql每小時查詢平均值

我想更改下面的查詢,以便能夠獲得每小時的平均值,而不是在x時間顯示存儲在數據庫中的值:00:00。

請幫

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 

這是查詢的

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 
+1

這麼多的嵌套選擇......我的午餐是回來了 – deed02392 2013-04-04 11:30:00

回答

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') 
+0

您的查詢結果仍然與我的查詢一樣。我想要一個查詢,首先從我的數據庫中的60個單個值中獲取一個小時的平均值,然後顯示所有其他傳感器的每個小時的平均值,即ph溫度固體和外部溫度 – Ossama 2013-04-05 15:23:44

+0

查詢應該使用類似SELECT DATE_FORMAT(x.time,'%Y-%m-%d%H:00:00') ,AVG(x.Ph)avg_Ph FROM Ph x其中time> = NOW() - INTERVAL 1 DAY GROUP BY DATE_FORMAT(x.time,'%Y-%m-%d%H:00:00'); – Ossama 2013-04-05 15:31:59