避免重复子查询

时间:2013-03-18 10:48:37

标签: sqlite

我的表消息包含 message_internaldate 列。现在,我想在几个月内的某些时间段(一天中的每个小时)内统计消息。通过拥有大量子查询,我可以设法获得每小时的消息总数(24),但我希望有更聪明的方法来做到这一点。除了时间段改变之外,子查询是相似的。有什么建议吗?

e.g。前两个小时

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 个答案:

答案 0 :(得分: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