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_id | Station_Name | Reaching_Timing | (No column name) |
---|---|---|---|
1 | sanfraneco | 10:30:00.0000000 | 0 |
2 | Newyork | 12:30:00.0000000 | 0 |
3 | chicago | 01:45:00.0000000 | 0 |
1条答案
按热度按时间kcugc4gi1#
You want the
LAG()
windowing function.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