这是一个很好的开始。这适用于任何日期/时间范围。但是,它有一个主要的先决条件:您需要创建一个包含您正在扫描的所有间隔 intervals
的字段的表。dt_hr datetime
Ex: '2011-12-25 00:00:00',
'2011-12-25 01:00:00',
'2011-12-25 02:00:00',
'2011-12-25 03:00:00',
. . .
'2011-12-25 23:00:00'
-
SELECT DATE_FORMAT(intervals.dt_hr,'%m/%d/%Y') AS Date,
EXTRACT(HOUR FROM intervals.dt_hr) AS Hour,
CASE
WHEN intervals.dt_hr > TIMESTAMPADD(HOUR,HOUR(s2.start_dts), DATE(s2.start_dts))
AND intervals.dt_hr < TIMESTAMPADD(HOUR,HOUR(s2.end_dts), DATE(s2.end_dts))
THEN 60
WHEN intervals.dt_hr = TIMESTAMPADD(HOUR,HOUR(s2.start_dts), DATE(s2.start_dts))
AND intervals.dt_hr < TIMESTAMPADD(HOUR,HOUR(s2.end_dts), DATE(s2.end_dts))
THEN 60 - EXTRACT(MINUTE FROM s2.start_dts)
WHEN intervals.dt_hr = TIMESTAMPADD(HOUR,HOUR(s2.end_dts), DATE(s2.end_dts))
AND intervals.dt_hr > TIMESTAMPADD(HOUR,HOUR(s2.start_dts), DATE(s2.start_dts))
THEN EXTRACT(MINUTE FROM s2.end_dts)
WHEN intervals.dt_hr = TIMESTAMPADD(HOUR,HOUR(s2.start_dts), DATE(s2.start_dts))
AND intervals.dt_hr = TIMESTAMPADD(HOUR,HOUR(s2.end_dts), DATE(s2.end_dts))
THEN EXTRACT(MINUTE FROM s2.end_dts) - EXTRACT(MINUTE FROM s2.start_dts)
ELSE 0
END AS MinutesOnLine
FROM intervals
LEFT JOIN sessions s2
ON intervals.dt_hr >= TIMESTAMPADD(HOUR,HOUR(s2.start_dts), DATE(s2.start_dts))
AND intervals.dt_hr <= TIMESTAMPADD(HOUR,HOUR(s2.end_dts), DATE(s2.end_dts))
要生成intervals
表,您可以创建一个存储过程,该过程创建一个具有 date_hour 序列的临时表。有关执行此操作的方法, 请参阅获取两个日期之间的日期列表。