简体   繁体   中英

How to calculate days/hours between dates in SQL

I have a SQL question. I have several rows below with two unique codes. How do I calculate days and hours in SQL sever? Basically, for each unique code, count the days and hours from the first DT_Time to the next DT_Time and so on. I was able to do this in Excel but for small set sample size.

    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. After that you can use DATEDIFF in order to calculate difference between 2 dates. Finalli using DATEPART you can calculate hour and days of difference Hope it will be useful

Use lag() and then 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM