我有一个包含START_DATE和END_DATE列的表。
我想检索每小时这些时间戳之间的平均时差,但仅在过去几天的上午9点到下午6点之间检索。我希望输出看起来像这样:
elapsed hour
-------------
2.5 11 <--today at 11AM
1.7 10
2.4 9
1.9 18 <--this is yesterday
2.4 17
4.0 16
我相信我非常接近,但我无法让代码工作。这就是我所拥有的:
SELECT
TRUNCATE(AVG(TIME_TO_SEC(TIMEDIFF(END_DATE, START_DATE))/60), 2) as elapsed,
EXTRACT(HOUR FROM END_DATE) as hour
FROM
TIME_INFO
WHERE
EXTRACT(HOUR FROM END_DATE) BETWEEN 9 AND 18 AND
DATE(END_DATE) > CURDATE() - INTERVAL 3 DAY
GROUP BY
EXTRACT(HOUR FROM END_DATE)
ORDER BY
END_DATE DESC
它很接近,但只返回我想要的三天前,而不是像我想的那样。我使用的是mySQL 5.0,有人有什么想法吗?
答案 0 :(得分:3)
如果您想要多天,则需要GROUP BY
子句中的日期和小时。目前它正在平均多天的同一小时的所有值。 (今天的11,昨天的11等等的值是平均值)
我没有一种简单的方法来测试它,但类似于:
SELECT
TRUNCATE(AVG(TIME_TO_SEC(TIMEDIFF(END_DATE, START_DATE))/60), 2) as elapsed,
EXTRACT(DAY FROM END_DATE) as day,
EXTRACT(HOUR FROM END_DATE) as hour
FROM
TIME_INFO
WHERE
EXTRACT(HOUR FROM END_DATE) BETWEEN 9 AND 18 AND
DATE(END_DATE) > CURDATE() - INTERVAL 3 DAY
GROUP BY
EXTRACT(DAY FROM END_DATE),
EXTRACT(HOUR FROM END_DATE)
ORDER BY
END_DATE DESC
如果您希望它跨月/年边界工作,您可能需要DATE(END_DATE)
而不是EXTRACT(DAY FROM END_DATE)
,在这种情况下输出可能如下所示:
elapsed date hour
-------------------------
2.5 2011/03/25 11 <--today at 11AM
1.7 2011/03/25 10
2.4 2011/03/25 9
1.9 2011/03/24 18 <--this is yesterday
2.4 2011/03/24 17
4.0 2011/03/24 16