[英]How to calculate days/hours between dates in SQL
I have a SQL question.我有一个 SQL 问题。 I have several rows below with two unique codes.我在下面有几行带有两个唯一代码。 How do I calculate days and hours in SQL sever?如何计算 SQL 服务器中的天数和小时数? Basically, for each unique code, count the days and hours from the first DT_Time to the next DT_Time and so on.基本上,对于每个唯一代码,计算从第一个 DT_Time 到下一个 DT_Time 的天数和小时数,依此类推。 I was able to do this in Excel but for small set sample size.我能够在 Excel 中做到这一点,但对于小样本量。
Code ID DT_TIME Day Hours
DA10637 18584080 5/17/2020 6:39:00 PM
DA10637 85902945 6/2/2020 11:34:00 PM 16 388.9166667
DA10637 18888989 6/5/2020 5:08:00 PM 3 65.56666667
DO10638 15840804 5/17/2020 6:39:00 PM
DO10638 85902971 6/2/2020 11:34:00 PM 16 388.9166667
DO10638 85928889 6/5/2020 5:08:00 PM 3 65.56666667
DO10638 18963688 6/15/2020 3:19:00 AM 9 226.1833333
You can use LAG function in order to have a relation with DT_TIME and DT_TIME of previous row.您可以使用 LAG function 以便与前一行的 DT_TIME 和 DT_TIME 建立关系。 After that you can use DATEDIFF in order to calculate difference between 2 dates.之后,您可以使用 DATEDIFF 来计算两个日期之间的差异。 Finalli using DATEPART you can calculate hour and days of difference Hope it will be useful Finalli使用DATEPART你可以计算小时和天的差异希望它会有用
Use lag()
and then datediff.使用lag()
然后 datediff。 For the difference in minutes, simply:对于分钟的差异,简单地说:
select t.*,
datediff(minute, lag(dt_time) over (partition by code order by dt_time), dt_time) as minutes_diff
from t;
I think that should be sufficient.我认为这应该足够了。 But you can split this into two columns using arithmetic:但是您可以使用算术将其分成两列:
select t.*,
floor(datediff(minute, lag(dt_time) over (partition by code order by dt_time), dt_time) / (24 * 60)) as days,
(datediff(minute, lag(dt_time) over (partition by code order by dt_time), dt_time) % (24 * 60)) / 60.0) as hours
from t;
The combination of LAG() Window Function and DATEDIFF should do the work. LAG() Window Function 和 DATEDIFF 的组合应该可以完成工作。
SELECT t.code, dt_time
, FLOOR(DATEDIFF(N, t.prev_dt_time, t.dt_time) / 60.0 / 24.0) AS days
, DATEDIFF(N, CASE WHEN CAST(dt_time AS date) > prev_dt_time THEN CAST(dt_time AS date) ELSE prev_dt_time END, dt_time) / 60.0 AS hours
FROM
(
SELECT code, dt_time, LAG(dt_time) OVER (PARTITION BY code ORDER BY dt_time ASC) AS prev_dt_time
FROM YourTable
) t
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.