我需要计算两个日期之间的小时数,其中一个是NOW(),不包括周末。 我已经找到了一些使用存储过程或mysql函数的解决方案,但我希望在一个查询中做到这一点。
我可以使用以下方法获取一般时差:
SELECT HOUR(TIMEDIFF(NOW(), created_at))
但是我需要它仅返回工作日的时间,而不是周末。因此,从星期五的23:00到星期一的1:00应该只相差2小时。
任何帮助将不胜感激。
谢谢!
MySQL 8
答案 0 :(得分:2)
在一种编程语言中,您将编写一个循环并通过迭代几天来总结小时。在SQL中,您可以对递归查询执行相同的操作:
with recursive cte (id, dt, minutes) as
(
select
id,
date(created_at),
case
when dayofweek(created_at) in (1, 7) then 0
else timestampdiff(minute, created_at, least(now(), date(created_at) + interval 1 day))
end
from mytable
union all
select
id,
dt + interval 1 day,
case
when dayofweek(dt + interval 1 day) in (1, 7) then 0
else timestampdiff(minute, dt + interval 1 day, least(now(), dt + interval 2 day))
end
from cte
where dt + interval 1 day <= curdate()
)
select id, round(sum(minutes) / 60, 1) as hours
from cte
group by id
order by id;
演示:https://dbfiddle.uk/?rdbms=mysql_8.0&fiddle=a08f96bc29fb8a51302da10679496e22