sql - 日期之间一天的小时数
问题描述
我有一个包含以下列的表:gkey、ata、atd
ata 和 atd 都是日期时间。
我想计算出每天有东西在它离开之前到达的时间。
示例数据:
+---------+-------------------------+-------------------------+
| gkey | ata | atd |
+---------+-------------------------+-------------------------+
| 1142227 | 14/06/2017 17:30:00.000 | 15/06/2017 05:30:00.000 |
+---------+-------------------------+-------------------------+
| 1322667 | 18/01/2018 16:17:00.000 | 18/01/2018 20:45:00.000 |
+---------+-------------------------+-------------------------+
| 1339468 | 26/02/2018 23:57:00.000 | 27/02/2018 11:35:00.000 |
+---------+-------------------------+-------------------------+
预期结果:
14/06/2017 - 6.5 hours
15/06/2017 - 5.5 hours
18/01/2018 - 4.5 hours
26/02/2018 - 0.05 hours
27/02/2018 - 11.58 hours
解决方案
您可以使用递归 CTE:
with cte as (
select gkey, ata, atd,
ata as day_start,
(case when cast(ata as date) = cast(atd as date)
then atd
else dateadd(day, 1, cast(ata as date))
end) as day_end
from t
union all
select gkey, day_end, atd,
day_end as day_start,
(case when cast(day_end as date) = cast(atd as date)
then day_end
else dateadd(day, 1, cast(day_end as date))
end) as day_end
from cte
where day_start < cast(atd as date)
)
select cte.*,
datediff(minute, day_start, day_end) / 60.0 as num_hours
from cte;
这是一个 SQL 小提琴。
推荐阅读
- html - 为什么我没有写H1之前有项目符号?
- android - 每当我更改其属性时,Android 线性布局都会不断重新排序子级
- android - MaterialDatePicker todayInUtcMilliseconds 方法返回不正确的日期
- node.js - 如何为所有响应添加中间件?(express.js)
- laravel - 如何选择用户的电子邮件来发送电子邮件?
- docker - Makefile 条件 PHONY 目标执行
- javascript - TypeError: DATA.total_cases 未定义,找不到错误?
- bash - Bash 脚本以 sudo 密码作为变量打开新的 gnome 终端
- android - 如何预填充 Android Room 数据库?
- c++ - 将指针类分配给新类,C++