我有一个基于CTE的查询,其中我检索两个给定时间间隔之间的小时间隔。我的查询工作如下:当时间戳的开始时间大于时间戳的结束时间时查询失败
获取开始和结束日期时间(比如说07-13-2011 00:21:09和07-31-2011 21:11:21)获得每小时间隔的小时总查询值(在这里是00到21,总共21小时,但这是参数化的,取决于我为输入提供的时间)。
此查询适用于第一个时间戳的小时小于第二个时间的输入 - 例如, 03 AM是第一个时间戳的时间,07 AM是第二个时间戳的时间,但是存在问题。当我想要检索输入的总计数时,如07-13-2011 22:11:43和07-25-2011 04:06:04,我遇到了问题。我需要检索以下查询的总计数:
07-13-2011 22:00:00 143 //representing the total amounts of queries 22:11:43 - 22:59:59 interval-
07-13-2011 23:00:00 121 //representing the total amounts of queries in 23:00:00 -23:59:59 interval-
07-14-2011 00:00:00 65 //00:00:00 - 00:59:59 interval
07-14-2011 01:00:00 51 //01:00:00 - 01:59:59 interval...
.
.
.
07-14-2011 04:00:00 22 //query amount for 04:00:00 - 04:06:04 interval
等等。除了我在下面写的CTE查询外,还需要做些什么?
WITH cal AS (
SELECT generate_series('2011-02-02 00:00:00'::timestamp
, '2012-04-01 05:00:00'::timestamp
, '1 hour'::interval) AS stamp
)
, qqq AS (
SELECT date_trunc('hour', calltime) AS stamp
, count(*) AS zcount
FROM mytable
WHERE calltime >= '07-13-2011 22:00:00'
AND calltime <='07-31-2011 04:33:21'
AND calltime::time >= '22:00:00'
AND calltime::time <= '04:33:21'
-- this calltime::time part obviously doesn't work due to common sense and logic
-- edited it to show what I try to mean
AND date_part('hour', calltime) >= 0
AND date_part('hour', calltime) <= 21
GROUP BY date_trunc('hour', calltime)
)
SELECT cal.stamp
, COALESCE (qqq.zcount, 0) AS zcount
FROM cal
LEFT JOIN qqq ON cal.stamp = qqq.stamp
WHERE cal.stamp >= '07-13-2011 22:00:00'
AND cal.stamp<='07-31-2011 04:33:21'
AND date_part('hour', cal.stamp) >= 0
AND date_part('hour', cal.stamp) <= 21
ORDER BY stamp ASC;
文本和示例在几个细节上相互矛盾(例如:是否要将结果中的小时数限制为“0-21”?)。我为我的答案选择了* one *解释并添加了可选的注释子句。 – 2012-08-15 12:35:57
@ErwinBrandstetter是的,我应该解决这个问题。我想限制小时数作为用户输入的时间间隔 - 这是在caltime和cal.stamp之间的calltime中给出的时间戳,在我的例子中是一天的22:00:00和另一天的04:32:21,在该时间间隔(包括输入日期)内的所有日子将显示22到04:32等部分之间的每小时查询计数。 – sm90901 2012-08-15 12:41:42
这仍然不明确:“在该时间间隔内的所有日子(包括输入日期)将显示22到04:32等部分之间的小时查询计数。”尝试清楚!你真的想在第一天包括00:00 - 04:32吗? – 2012-08-15 13:24:18