サンプルデータは次のとおりです。
シリアルナンバー |
時間 |
場所 |
1 |
9:00 |
あ |
2 |
9:01 |
あ |
3 |
9:03 |
あ |
4 |
9:04 |
B |
5 |
9:09 |
あ |
要件の結果: 隣接する時刻と場所が同じデータは 1 つのグループにグループ化され、異なる時点のデータは別のグループにグループ化されます。つまり、通し番号 1、2、3 がグループを形成し、通し番号 4 がグループを形成し、通し番号 5 がグループを形成します。
参考結果:
シリアルナンバー |
時間 |
場所 |
グループ |
1 |
9:00 |
あ |
1 |
2 |
9:01 |
あ |
1 |
3 |
9:03 |
あ |
1 |
4 |
9:04 |
B |
2 |
5 |
9:09 |
あ |
3 |
リファレンス実装:
WITH t as (
select 1 as id,'9:00' as date_time ,'A' as location union all
select 2 as id,'9:01' as date_time ,'A' as location union all
select 3 as id,'9:03' as date_time ,'A' as location union all
select 4 as id,'9:04' as date_time ,'B' as location union all
select 5 as id,'9:09' as date_time ,'A' as location
)
select
id
,date_time
,location
,per_location
,new_group_flag
,sum(new_group_flag) over(order by id) as group_id --最终分组id
from
(
select id,date_time,location,per_location,case when location=per_location then 0 else 1 end as new_group_flag from
(
select id,date_time,location,lag(location,1) over(order by id) as per_location from t
) t
) t1
;
+-----+------------+-----------+---------------+-----------------+-----------+--+
| id | date_time | location | per_location | new_group_flag | group_id |
+-----+------------+-----------+---------------+-----------------+-----------+--+
| 1 | 9:00 | A | NULL | 1 | 1 |
| 2 | 9:01 | A | A | 0 | 1 |
| 3 | 9:03 | A | A | 0 | 1 |
| 4 | 9:04 | B | A | 1 | 2 |
| 5 | 9:09 | A | B | 1 | 3 |
+-----+------------+-----------+---------------+-----------------+-----------+--+