响应查询将按保持结果集中给定顺序的某个字段排序,以使查询正常工作。
您将在数据中查找当前值为 0 且先前值为 1 的模式,并开始一个新的 grp,如下所示。
这是一种方法。
create table t(id int, dest int, emp int);
insert into t
select 1,893106,0 union all
select 2,717205,1 union all
select 3,888305,0 union all
select 4,312301,1 union all
select 5,645100,0 union all
select 6,222001,0 union all
select 7,761104,1;
commit;
with main_data
as (
select *,case when emp=0 and lag(emp) over(order by id)=1 then
1
else 0
end as grp_val
from t
)
select *,sum(grp_val) over(order by id) as grp
from main_data;
+====+========+=====+=========+=====+
| id | dest | emp | grp_val | grp |
+====+========+=====+=========+=====+
| 1 | 893106 | 0 | 0 | 0 |
+----+--------+-----+---------+-----+
| 2 | 717205 | 1 | 0 | 0 |
+----+--------+-----+---------+-----+
| 3 | 888305 | 0 | 1 | 1 |
+----+--------+-----+---------+-----+
| 4 | 312301 | 1 | 0 | 1 |
+----+--------+-----+---------+-----+
| 5 | 645100 | 0 | 1 | 2 |
+----+--------+-----+---------+-----+
| 6 | 222001 | 0 | 0 | 2 |
+----+--------+-----+---------+-----+
| 7 | 761104 | 1 | 0 | 2 |
+----+--------+-----+---------+-----+
https://sqlize.online/sql/psql14/053971a469e423ef65d97984f9017fbf/