Unfortunately I don't have a lot of experience with SQL Server.
I have a table with the following structure and sample data:
| ID | Status | TimeStamp |
|---|---|---|
| 68 | 2 | 10.01.2022 08:45:02 |
| 52 | 0 | 10.01.2022 08:44:29 |
| 50 | 0 | 10.01.2022 08:41:12 |
| 46 | 0 | 10.01.2022 08:41:02 |
| 40 | 1 | 10.01.2022 08:40:07 |
| 38 | 2 | 10.01.2022 08:20:05 |
| 32 | 0 | 10.01.2022 08:19:29 |
| 30 | 1 | 10.01.2022 08:15:34 |
What I have to do now is the timestamp where the status 1 is as start, the timestamp of status 2 as the end and count the entries with 0 in between. Unfortunately the entries are not consecutive. So I can't just count the ID forwards or backwards. The result should look like this:
| Start | End | CountStatus0 |
|---|---|---|
| 10.01.2022 08:40:07 | 10.01.2022 08:45:02 | 3 |
| 10.01.2022 08:15:34 | 10.01.2022 08:20:05 | 1 |
I would be very grateful for a suggestion on how to best solve this.
I already tried to solve it with the group by function but I had no success yet.
CodePudding user response:
You've tagged SQL Server 2008 - I believe the following is compatible, of course unable to test.
You can use a lateral join (cross apply) to find the corresponding end timestamp that applies to each row.
Then simply aggregate by the end timestamp and count rows where the status is zero.
with e as (
select t.timestamp tstart, e.timestamp tend
from t
cross apply (
select Min(timestamp) timestamp
from t t2
where t2.status=2
and t2.timestamp > t.timestamp
)e
where status=0
)
select Min(tstart) [Start], Max(tend) [end], count(*) CountStatus0
from e
group by tend
order by [start] desc
See example Fiddle
