我想查詢的平均列值在表中按小時過去24小時。我有甚至沒有記錄的時間顯示結果的麻煩(在這種情況下,我應該打印0的平均值)MySQL的按小時得到記錄數,連時間沒有記錄
這是我到目前爲止有:
SELECT HOUR(time), AVG(score) FROM place_rvw WHERE time >= NOW() - INTERVAL 1 DAY AND place_id = 1 ORDER BY HOUR(time);
現在(12點),例如,我的唯一記錄是9PM和10PM。因此,結果中只有兩行。我希望它有24行(代表過去24小時中的每一行),如果一個小時沒有記錄,則只顯示0的平均值。
任何形式的幫助表示讚賞。謝謝!
編輯 我試過下面喜歡什麼斯蒂芬提出的查詢,但它仍然顯示了同樣的結果。理想的結果應該有24行代表每個小時。有什麼建議麼?
SELECT za_hours.za_hour as hour, AVG(IFNULL(score,0)) as average_score
FROM (
SELECT 0 as za_hour
UNION
SELECT 1 as za_hour
UNION
SELECT 2 as za_hour
UNION
SELECT 3 as za_hour
UNION
SELECT 4 as za_hour
UNION
SELECT 5 as za_hour
UNION
SELECT 6 as za_hour
UNION
SELECT 7 as za_hour
UNION
SELECT 8 as za_hour
UNION
SELECT 9 as za_hour
UNION
SELECT 10 as za_hour
UNION
SELECT 11 as za_hour
UNION
SELECT 12 as za_hour
UNION
SELECT 13 as za_hour
UNION
SELECT 14 as za_hour
UNION
SELECT 15 as za_hour
UNION
SELECT 16 as za_hour
UNION
SELECT 17 as za_hour
UNION
SELECT 18 as za_hour
UNION
SELECT 19 as za_hour
UNION
SELECT 20 as za_hour
UNION
SELECT 21 as za_hour
UNION
SELECT 22 as za_hour
UNION
SELECT 23 as za_hour
) za_hours
LEFT JOIN place_rvw
ON za_hours.za_hour = HOUR(time)
AND
time >= NOW() - INTERVAL 1 DAY
AND place_id = 1
GROUP BY
za_hours.za_hour
ORDER BY za_hours.za_hour
行不包含0,那個時間段沒有行。 –
啊我誤解了那部分。 – Screech129
感謝您的回答。爲什麼我添加了條款AND place_id = 1的原因是因爲我只想顯示具有該外鍵的結果。用OR替換AND會產生不正確的結果。 – galibee