I have a list of Date Times values stored in a SQL SERVER Table.
I have to calculate the Arrival Date time and Departure Date Time list:
- Each arrival and departure occur in the same Day date
- Departure date is the first record of a day, Arrival Date is the next record in the same day if exists, then the next record is an Arrival date
Here is an example of Data
set dateformat dmy
declare @mytable as table (MyEvent datetime)
insert into @mytable values
('01/01/2022 08:15'),
('01/01/2022 10:20'),
('01/01/2022 18:37'),
('02/01/2022 09:15'),
('02/01/2022 20:05'),
('02/01/2022 23:28'),
('02/01/2022 06:32'),
('04/01/2022 10:15'),
('05/01/2022 11:39');
The out put should be as follows
I have done the following script which makes the calculation , but I'm asking if there is another more performant way before I implement the solution in a Table with millions of records
with cte1 as
(select CAST(MyEvent as date) Mydate,MyEvent from @mytable),
cte2 as
(select MyDate,MyEvent,ROW_NUMBER() over(partition by MyDate order by Mydate) R# from cte1),
cte3 as
(select cte21.MyDate,cte21.Myevent Departure,
cte22.Myevent Arrival from cte2 cte21
left outer join cte2 cte22 on cte21.Mydate=cte22.Mydate and cte21.R#+1=cte22.R#
where cte21.R# % 2 =1
)
select * from cte3