SQL Server I can't able to write a sql query for one requirements

qvtsj1bj  于 2023-04-10  发布在  其他
关注(0)|答案(1)|浏览(132)

In a sql server table contains train_id,station_name and Reaching_time. so I want to add one more column while using select query. that column is duration. so first station reaching time and second station reaching time there so simply we want to minus then we will got the duration. but I can't able to achive it. so I attached my query but I got null value in duration column. Please refer below screenshot.

Query:

select
    t1.train_id, t1.Station_Name, t1.Reaching_Timing, DATEDIFF(MINUTE,t1.Reaching_Timing,t2.Reaching_Timing) 
from train_schudle t1
left join train_schudle t2
    on t1.train_id=t2.train_id
group by t1.train_id, t1.Station_Name, t1.Reaching_Timing,t2.train_id, t2.Station_Name, t2.Reaching_Timing;

I'm getting only null value in duration column so I want to correct duration time in that duration column.

train_idStation_NameReaching_Timing(No column name)
1sanfraneco10:30:00.00000000
2Newyork12:30:00.00000000
3chicago01:45:00.00000000
kcugc4gi

kcugc4gi1#

You want the LAG() windowing function.

SELECT train_id, Station_Name, Reaching_Time, 
   DateDiff(minute, LAG(Reaching_time) OVER (PARTITION BY train_id ORDER BY reaching_time), Reaching_Time) Duration
FROM train_schedule

This assumes the Reaching_time is a reasonable data type, and not a string/varchar column.

But note: I would expect null values based on the sample data, since these are different trains. If you want to see results, use the same train_id in a few of the sample data rows, so you can follow the same train from one stop to the next. You can see that effect here:
https://dbfiddle.uk/tTqKnXqS

相关问题