I am trying to figure out how to do this with either LINQ or SQL.
I have a table called Activity, a process continously logs to it every day. This process checks for a certain condition (Found or Not). My table data looks like:
Date | Found |
---|---|
1/1/2021 | 0 |
1/2/2021 | 0 |
1/3/2021 | 1 |
1/4/2021 | 1 |
1/5/2021 | 0 |
1/6/2021 | 0 |
1/7/2021 | 0 |
1/8/2021 | 0 |
1/9/2021 | 0 |
I would like to reduce this result to show when a transition has occurred and the previous record (previous day):
Date | Found |
---|---|
1/2/2021 | 0 |
1/3/2021 | 1 |
1/5/2021 | 0 |
The only solution I can think of is to do a loop in C# and check for the changes and record them in a new collection. But I would really like to know if something like this is possible with SQL or LINQ.
Hmmm. . . you seem to want rows where the row, the previous row, or the next row has found = 1
. One method uses lag()
and lead()
:
select t.*
from (select t.*,
lag(found) over (order by date) as prev_found,
lead(found) over (order by date) as next_found
from t
) t
where 1 in (prev_found, found, next_found);
You can also use a window frame:
select t.*
from (select t.*,
sum(found) over (order by date rows between 1 preceding and 1 following) as num_found
from t
) t
where num_found > 0;
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.