I wanted to manipulate the end date to next record startdate or records that happened on same day for shopID and then grab the starttime of later record and update the value in the prior row endtime if the starttime prior to next row start time and end date crosses the next record start date. The key columns to use will be shopid, starttime,endtime.
Note: 1) For example (PurchaseID:20200102) end date of first record is '2020-01-08 09:18:52' which is crosses the start time of next record '2020-01-08 09:09:48'. Here my logic need to look for such instances happen on same day and manipulate the enddate of first record to next record startdate 2) I would like this change to happen only on the records that occurred on same day. To be precise the records with same startdates but overlapping the enddates. 3) There are scenarios where both records start at same time example store id 1023, 1024. In this scenario I would like the end date one record manipulated to next record. To be precise the startdate and enddate will be same for one record as shown in final result set. 4) I would like this change to happen only on the records that occurred on same day. To be precise the records with same startdates but overlapping the enddates excluding the timestamp.
CREATE TABLE [dbo].[TestTab1](
StoreID [int] NOT NULL,
PurchaseID [int] NOT NULL,
LocationID [int] NOT NULL,
starttime [datetime] NOT NULL,
Endtime [datetime] NOT NULL,
) ON [PRIMARY]
INSERT INTO [TestTab1]
VALUES
(1020,20200102,10,'2020-01-08 09:08:53','2020-01-08 09:18:52'),
(1021,20200102,20,'2020-01-08 09:09:48','2020-01-08 09:11:52'),
(1022,20200102,30,'2020-01-08 09:12:53','2020-01-08 09:14:52'),
(1023,20200104,40,'2020-10-08 09:16:48','2020-10-08 09:48:21'),
(1024,20200104,60,'2020-10-08 09:16:48','2020-10-08 09:20:22')
Final Result set:
StoreID PurchaseID LocationID starttime Endtime
1020 20200102 10 2020-01-08 09:08:53 2020-01-08 09:09:48
1021 20200102 20 2020-01-08 09:09:48 2020-01-08 09:11:52
1022 20200102 30 2020-01-08 09:12:53 2020-01-08 09:14:52
1023 20200104 40 2020-10-08 09:16:48 2020-10-08 09:16:48
1024 20200104 60 2020-10-08 09:16:48 2020-01-08 09:20:22
Thanks in advance!