0
所以基本上我需要在經過48個小時的小時基礎上產生一個報告。 對於任何空時我想返回0爲total_videos
和time_in_seconds
。按小時計算包括空時在內的行數?
但我的嘗試似乎並沒有被返回空行,而不是我得到:
period total_videos time_in_seconds
Apr 10th 14 00:00-00:59 11 406.00
Apr 10th 14 02:00-02:59 5 70.00
Apr 10th 14 03:00-03:59 10 110.00
Apr 10th 14 06:00-06:59 1 85.40
Apr 10th 14 07:00-07:59 4 103.00
Apr 10th 14 08:00-08:59 5 292.44
Apr 10th 14 12:00-12:59 1 2258.52
Apr 10th 14 21:00-21:59 5 5189.33
Apr 10th 14 22:00-22:59 1 182.39
Apr 10th 14 23:00-23:59 9 119.16
Apr 11th 14 03:00-03:59 1 2039.13
下面是該查詢。
#Create a table of all 24 hours
DROP TABLE IF EXISTS hours;
CREATE TEMPORARY TABLE hours (`hour` INT);
INSERT INTO hours (`hour`) VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12),(13),(14),(15),(16),(17),(18),(19),(20),(21),(22),(23);
#Create a table that contains todays date, yesterdays date, and the day before (48 hours)
DROP TABLE IF EXISTS dates;
CREATE TEMPORARY TABLE dates (`date` DATE);
INSERT INTO dates(`date`) VALUES (DATE(NOW())), (DATE(NOW() - INTERVAL 24 HOUR)), (DATE(NOW() - INTERVAL 48 HOUR));
SELECT
DATE_FORMAT(v.`created_at`,'%b %D %y %H:00-%H:59') AS period,
COUNT(v.created_at) AS `total_videos`,
SUM(v.duration) AS `time_in_seconds`
FROM videos AS v
RIGHT OUTER JOIN hours AS h ON HOUR(v.`created_at`) = h.hour
RIGHT OUTER JOIN dates AS d ON DATE(v.`created_at`) = d.date
WHERE v.created_at IS NULL OR DATE(v.created_at) >= (SYSDATE() - INTERVAL 48 HOUR)
GROUP BY d.date, h.hour
ORDER BY d.date, h.hour ASC;
您不需要創建臨時表,最好使用sys.objects或類似的select row_number()來生成一些東西。我會首先考慮做一個更簡單的查詢,因爲問題看起來是在外連接 - 可能是左外連接。 – kayakpim