Hi @Rob Jarrett ,
Please refer below:
WITH CTE AS (
SELECT '2020-11-02 06:00:34.000' ActionDate, 1 IsIngress UNION ALL
SELECT '2020-11-02 06:01:15.000' ActionDate, 1 IsIngress UNION ALL
SELECT '2020-11-02 08:26:38.000' ActionDate, 0 IsIngress UNION ALL
SELECT '2020-11-02 08:29:26.000' ActionDate, 1 IsIngress UNION ALL
SELECT '2020-11-02 11:41:44.000' ActionDate, 0 IsIngress UNION ALL
SELECT '2020-11-02 11:42:39.000' ActionDate, 1 IsIngress UNION ALL
SELECT '2020-11-02 11:48:17.000' ActionDate, 1 IsIngress UNION ALL
SELECT '2020-11-02 16:21:53.000' ActionDate, 0 IsIngress)
select ActionDate, IsIngress,
row_number() over (partition by IsIngress, grp order by ActionDate) as row_num
from (select t.*,
(row_number() over (order by ActionDate) -
row_number() over (partition by IsIngress order by ActionDate)
) as grp
from CTE t
) t
order by ActionDate
Output:
ActionDate IsIngress row_num
2020-11-02 06:00:34.000 1 1
2020-11-02 06:01:15.000 1 2
2020-11-02 08:26:38.000 0 1
2020-11-02 08:29:26.000 1 1
2020-11-02 11:41:44.000 0 1
2020-11-02 11:42:39.000 1 1
2020-11-02 11:48:17.000 1 2
2020-11-02 16:21:53.000 0 1
The final:
;WITH CTE AS (
SELECT '2020-11-02 06:00:34.000' ActionDate, 1 IsIngress UNION ALL
SELECT '2020-11-02 06:01:15.000' ActionDate, 1 IsIngress UNION ALL
SELECT '2020-11-02 08:26:38.000' ActionDate, 0 IsIngress UNION ALL
SELECT '2020-11-02 08:29:26.000' ActionDate, 1 IsIngress UNION ALL
SELECT '2020-11-02 11:41:44.000' ActionDate, 0 IsIngress UNION ALL
SELECT '2020-11-02 11:42:39.000' ActionDate, 1 IsIngress UNION ALL
SELECT '2020-11-02 11:48:17.000' ActionDate, 1 IsIngress UNION ALL
SELECT '2020-11-02 16:21:53.000' ActionDate, 0 IsIngress)
,cte2 as (
select ActionDate, IsIngress,
row_number() over (partition by IsIngress, grp order by ActionDate) as row_num
from (select t.*,
(row_number() over (order by ActionDate) -
row_number() over (partition by IsIngress order by ActionDate)
) as grp
from CTE t
) t)
select * from cte2 where row_num=1 order by ActionDate
Output:
ActionDate IsIngress row_num
2020-11-02 06:00:34.000 1 1
2020-11-02 08:26:38.000 0 1
2020-11-02 08:29:26.000 1 1
2020-11-02 11:41:44.000 0 1
2020-11-02 11:42:39.000 1 1
2020-11-02 16:21:53.000 0 1
Best regards
Melissa
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.
Hot issues November--What can I do if my transaction log is full?
Hot issues November--How to convert Profiler trace into a SQL Server table