I have a device details as below.
The Dtatus column will have ON or OFF Status. When a device is plugged in, it will continously generate "ON" values. When it is disconnected it will show "OFF" Status.
When Status column is having "ON" value, we need to update StartDate of the first row of "ON" Value with Date column value. EndDate needs to update with the next "OFF" value date. We need to update dates when it is connected/disconnect.
I need to generate a SQL query for updating Dates for "ON" and OFF Status. I cannot use cursor. I have tried using row_number
, but not able to partition by ON/OFF values. Any help is appreciated.
Expected resut is shown as values in StartDate and EndDate.
Test table and data
create table #test (
ID int,
Date datetime,
Status nvarchar(3),
StartDate datetime,
EndDate datetime
)
insert into #test(ID, Date, status, StartDate, EndDate)
select 1 ,'12-06-2023 00:00:00', 'ON',null,null
union all select 1 ,'12-07-2023 00:00:00', 'ON',null,null
union all select 1 ,'12-08-2023 00:00:00', 'OFF',null,null
union all select 1 ,'12-09-2023 00:00:00', 'ON',null,null
union all select 1 ,'12-10-2023 00:00:00', 'OFF',null,null
3条答案
按热度按时间x3naxklr1#
So, you can use analytical functions to group the desired records and find
MAX
andMIN
dates to calculate required columnsSTART_DATE
andEND_DATE
as follows:Please adjust column names or minor changes as required.
With Multiple IDs:
qpgpyjmq2#
You have a gaps and islands problem here, you could use the difference between two row_numbers approach to solve it :
Results :
Explanations :
First
cte
used to identify different groups based on successive identical status.cte2/cte3 used to order generated groups so it can be easy to group successive groups together (ON and OFF) using the arithmetic
(ordered_grp - 1 )/2
cte4 used to get min and max date per group, which will contains data with ON and OFF status
Demo here
rdlzhqv93#
The direct way is to count up the OFF statuses. By doing it in reverse order you naturally get each OFF as the beginning of each logical partition.