SQL:几天内、两次之间的平均每小时
我有一个包含 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,有人有什么想法吗?
I have a table that has a START_DATE and an END_DATE column.
I want to retrieve the average time difference between these timestamps for each hour, but only between the hours of 9AM to 6PM, over the course of the last few days. I'd like the output to look like this:
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
I believe I am quite close, but I just can't get the code to work. Here is what I have:
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
It is close, but only returns what I want from three days ago instead of across days like I'd like. I am using mySQL 5.0, anyone have any ideas?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您想要多天,则需要在
GROUP BY
子句中提供日期和小时。目前,它正在对多天同一小时的所有值进行平均。 (今天 11 点、昨天 11 点等的值一起平均)我没有简单的方法来测试它,但是类似:
如果您希望它跨月/年边界工作,您可能需要
DATE(END_DATE)
而不是EXTRACT(DAY FROM END_DATE)
,在这种情况下,输出可能类似于:If you want multiple days you will need the day as well as hour in the
GROUP BY
clause. Currently it's averaging all the values for the same hour on multiple days. (Values for today's 11, yesterday's 11, etc., are averaged together)I don't have an easy way to test it, but something like:
If you want it to work across month/year boundaries you'll probably want
DATE(END_DATE)
rather than theEXTRACT(DAY FROM END_DATE)
, in which case output might look something like: