Hi @red ,
I am not sure what the logic of these two data updates is, so I give my update logic:
CREATE TABLE [dbo].[TestTab1](
StoreID [int] NOT NULL,
PurchaseID [int] NOT NULL,
ShopID [int] NOT NULL,
LocationID [int] NOT NULL,
starttime [datetime] NOT NULL,
Endtime [datetime] NOT NULL,
) ON [PRIMARY]
INSERT INTO [TestTab1]
VALUES (1020,20200102,9856,0010,'2020-01-08 09:08:53','2020-01-08 09:11:52'),
(1021,20200102,9856,0020,'2020-01-08 09:09:48','2020-01-08 09:11:52'),
(1022,20200102,9856,0030,'2020-01-09 09:08:53','2020-01-09 09:11:52'),
(1023,20200102,9856,0040,'2020-01-10 09:09:48','2020-01-10 09:11:52')
; WITH cte AS (
SELECT *, row_number() OVER(PARTITION BY shopid, purchaseID ORDER BY Starttime) AS rn
FROM [dbo].[TestTab1])
UPDATE a
SET a.EndTime = b.Starttime
FROM cte a
JOIN cte b ON a.Shopid = b.Shopid
AND a.PurchaseID = b.purchaseID
AND a.rn = b.rn -1
AND datepart(dd,a.Starttime)=datepart(dd,b.Starttime)
WHERE a.Locationid <> b.Locationid
; WITH cte AS (
SELECT *, row_number() OVER(PARTITION BY datepart(dd,Starttime) ORDER BY Starttime) AS rn
FROM [dbo].[TestTab1])
update a
set a.EndTime = dateadd(mi,datepart(dd,Starttime)-8,EndTime)
from cte a
where datepart(dd,Starttime) not in (select datepart(dd,Starttime) from cte where rn>1)
select * from [dbo].[TestTab1]
drop table [dbo].[TestTab1]
In addition, what is the relationship between your existing data and the final Result set?
If you have any question, please feel free to let me know.
If the response is helpful, please click "Accept Answer" and upvote it.
Best Regards
Echo
If the answer is helpful, please click "Accept Answer" and upvote it.
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.