2013-03-18 219 views
0

我有一個表消息包含一列message_internaldate。現在我想在幾個月內的特定時間段內(一天中的每個小時)對這些消息進行計數。我可以設法通過大量的子查詢來獲得每小時的消息總數(24),但我希望有一個更聰明的方式來做到這一點。除了時間段發生變化外,子查詢是相似的。有什麼建議麼?避免重複子查詢

例如前兩個小時

SELECT T1, T2 FROM 
(
SELECT sum(T1c) as T1 FROM 
    (
    SELECT strftime('%H:%M',message_internaldate) AS T1s ,count(*) as T1c FROM messages WHERE 
    message_internaldate BETWEEN '2005-01-01 00:00:00' AND '2012-12-31 00:00:00' 
    AND strftime('%H:%M',message_internaldate) BETWEEN '01:00'AND '01:59' 
    GROUP BY strftime('%H:%M',message_internaldate) 
    ) 
) 
, 
(
SELECT sum(T2c) as T2 FROM 
    (
    SELECT strftime('%H:%M',message_internaldate) AS T2s ,count(*) as T2c FROM messages WHERE 
    message_internaldate BETWEEN '2005-01-01 00:00:00' AND '2012-12-31 00:00:00' 
    AND strftime('%H:%M',message_internaldate) BETWEEN '02:00'AND '02:59' 
    GROUP BY strftime('%H:%M',message_internaldate) 
    ) 
) 
... 

回答

1

你的問題是,你想有個別小時爲列。

爲了讓他們爲行,嘗試這樣的查詢:

SELECT strftime('%H', message_internaldate) AS hour, 
     strftime('%H:%M', message_internaldate) AS Ts, 
     COUNT(*) AS Tc 
FROM messages 
WHERE message_internaldate BETWEEN '2005-01-01 00:00:00' AND '2012-12-31 23:59:59' 
GROUP BY 1, 2 
+0

謝謝!我說: 選擇時,總和(TC)爲SumOfMails FROM ( 您的查詢 )GROUP BY小時 這不正是我原本想做的事! – Durin 2013-03-18 11:31:25