sql - SQL Query to calculate the hours between two dates grouped by days
问题描述
I need to write an SQL query for the following scenario.
I am having start date as 2020-01-10 13:00:00.347 and end date as 2020-01-12 02:00:00.347, so I need data grouped as
Day Hours
---- -----
10-01-2020 11
11-01-2020 24
12-01-2020 2.30
which means 11 hours was for the first date and 24 hours in second day and 2.3 hours on 3rd day.
What will the most Efficient SQL query to fetch the data in the above-mentioned format? Thanks in advance.
解决方案
您可以使用递归 CTE 将日期分解为范围:
with recursive cte as (
select start_date as day_start,
(case when date(start_date) = date(end_date) then end_date else date(start_date) + interval 1 day end) as day_end,
end_date
from (select cast('2020-01-10 13:00:00.347' as datetime) as start_date,
cast('2020-01-12 02:00:00.347' as datetime) as end_date
) t
union all
select day_end,
(case when date(day_end) = date(end_date) then end_date else date(day_end) + interval 1 day end) as day_end,
end_date
from cte
where day_end <> end_date
)
select day_start, day_end,
timestampdiff(second, day_start, day_end) / (60 * 60)
from cte;
这是一个 db<>fiddle。
编辑:
在 SQL Server 中,这看起来像:
with cte as (
select start_date as day_start,
(case when cast(start_date as date) = cast(end_date as date) then end_date else dateadd(day, 1, cast(start_date as date)) end) as day_end,
end_date
from (select cast('2020-01-10 13:00:00.347' as datetime) as start_date,
cast('2020-01-12 02:00:00.347' as datetime) as end_date
) t
union all
select day_end,
(case when cast(day_end as date) = cast(end_date as date) then end_date else dateadd(day, 1, day_end) end) as day_end,
end_date
from cte
where day_end <> end_date
)
select day_start, day_end,
datediff(second, day_start, day_end) / (60.0 * 60)
from cte;
这是这个 db<>fiddle。
推荐阅读
- ruby-on-rails - ActiveAdmin 去除花括号内的内容
- vuejs2 - Vuetify 如何根据需要标记字段
- xcode - Apple App ID 在 Xcode 9 和 Developer Portal 中不起作用
- synchronization - 与 Zimbra 日历的完整日历同步
- mysql - 如果在 Mysql 中不存在具有唯一 ID 的记录,则返回 0 值记录
- ios - 仅当我使用约束布局在 IOS 中滚动时才能获得正确的视图
- sql-server - 托管 SQL Server,使用 Windows 计划任务
- bash - bash 单独工作,但在屏幕中运行时失败
- javascript - 延迟设置后,如何在其 href 设置后单击锚标记?
- jquery - 如何使用 jQuery 在输入字段值中只接受整数和浮点数等数字