想象一下如下的mysql表:
Interval
--------------------------
id INT, NOT NULL
start DATETIME, NOT NULL
finish DATETIME, NOT NULL
我想要一个有效的查询,它会产生一系列天数中午的间隔数。如果我的数据看起来像这样:
id start finish
-------------------------------------------------
1 2013-01-12 08:00:00 2013-01-17 02:00:00
2 2013-01-12 15:00:00 2013-01-13 18:00:00
3 2013-01-13 08:00:00 2013-01-13 09:00:00
4 2013-01-14 11:00:00 2013-01-15 08:00:00
5 2013-01-14 02:00:00 2013-01-17 01:00:00
6 2013-01-15 20:00:00 2013-01-16 08:00:00
我可以运行它并收到如下结果集:
Timestamp Count
-----------------------------
2013-01-12 12:00:00 1
2013-01-13 12:00:00 2
2013-01-14 12:00:00 3
2013-01-15 12:00:00 2
2013-01-16 12:00:00 2
我可以通过查询最小开始和最大结束来做到这一点,然后这样做:
SELECT count(id) FROM Interval
WHERE start <= @noon_timestamp AND finish >= @noon_timestamp
对于范围内的每一天,但这似乎是丑陋和可怕的。
有没有办法做得更好?如果是这样,你能用SqlAlchemy的语法吗? :)
答案 0 :(得分:0)
您可以使用BETWEEN
:
SELECT COUNT(*)
FROM Interval
WHERE @noon_timestamp BETWEEN start AND finish