我有類似這樣的一個collcation:按小時分組時,應返回0。這個怎麼做?
http://sqlfiddle.com/#!2/fecbc/3
我的問題是,當我使用group by HOUR(date)
小時像2
,3
和4
出現,但與0
我想。
其實他們消失的結果。
我該如何執行此操作?
什麼是簡單的方法來做到這一點?
有沒有辦法避免24 ifs陳述?
我們可以避免創建另一個表嗎?
我有類似這樣的一個collcation:按小時分組時,應返回0。這個怎麼做?
http://sqlfiddle.com/#!2/fecbc/3
我的問題是,當我使用group by HOUR(date)
小時像2
,3
和4
出現,但與0
我想。
其實他們消失的結果。
我該如何執行此操作?
什麼是簡單的方法來做到這一點?
有沒有辦法避免24 ifs陳述?
我們可以避免創建另一個表嗎?
您需要一個包含24小時的表格,然後JOIN
。如果您無法創建表格,則可以在查詢中創建它。 See this demo。
SELECT a.hr, IFNULL(b.hourCount, 0) hourCount
FROM
(SELECT 1 AS hr
UNION ALL
SELECT 2
UNION ALL
SELECT 3
UNION ALL
SELECT 4
UNION ALL
SELECT 5
UNION ALL
SELECT 6
UNION ALL
SELECT 7
UNION ALL
SELECT 8
UNION ALL
SELECT 9
UNION ALL
SELECT 10
UNION ALL
SELECT 11
UNION ALL
SELECT 12
UNION ALL
SELECT 13
UNION ALL
SELECT 14
UNION ALL
SELECT 15
UNION ALL
SELECT 16
UNION ALL
SELECT 17
UNION ALL
SELECT 18
UNION ALL
SELECT 19
UNION ALL
SELECT 20
UNION ALL
SELECT 21
UNION ALL
SELECT 22
UNION ALL
SELECT 23
UNION ALL
SELECT 0) a
LEFT JOIN
(SELECT COUNT(id) AS hourCount, HOUR(date) AS hr
FROM `testing`
GROUP BY HOUR(date)) b ON b.hr = a.hr
如果您想要前導零,請在您的查詢中使用lpad。
SELECT
COUNT(id) AS hourCount,
lpad(HOUR(date),2,'0') AS hour
FROM
testing
GROUP BY
HOUR(date)
;
OP希望缺少小時。 – Kermit 2013-05-07 15:06:55
如果您不希望創建這樣的表,你可以使用從0到23枚舉小時的子查詢:
SELECT
v_hours.hr as hour,
COUNT(id) AS hourCount
FROM
(select 0 as hr union all
select 1 as hr union all
select 2 as hr union all
select 3 as hr union all
select 4 as hr union all
select 5 as hr union all
select 6 as hr union all
select 7 as hr union all
select 8 as hr union all
select 9 as hr union all
select 10 as hr union all
select 11 as hr union all
select 12 as hr union all
select 13 as hr union all
select 14 as hr union all
select 15 as hr union all
select 16 as hr union all
select 17 as hr union all
select 18 as hr union all
select 19 as hr union all
select 20 as hr union all
select 21 as hr union all
select 22 as hr union all
select 23 as hr
) v_hours
LEFT JOIN testing
ON HOUR(date) = v_hours.hr
GROUP BY
v_hours.hr
ORDER BY v_hours.hr
您也處理在應用程序級別缺少結果的邏輯。 – Strawberry 2013-05-07 15:36:08