组顺序重复值sqlite
Group sequential repeated values sqlite
我有按顺序重复的数据..
A
A
A
B
B
B
A
A
A
我需要这样分组
A
B
A
使用 sqlite 执行此操作的最佳方法是什么?
假设您有一个定义行顺序的列,例如 id
,您可以使用 window 函数解决此 gaps-and-island 问题:
select col, count(*) cnt, min(id) first_id, max(id) last_id
from (
select t.*,
row_number() over(order by id) rn1,
row_number() over(partition by col order by id) rn2
from mytable t
) t
group by col, rn1 - rn2
order by min(id)
我在结果集中添加了几列,以提供有关每组内容的更多信息。
如果您定义了定义行顺序的列,例如 id
,您可以使用 window 函数 LEAD()
:
select col
from (
select col, lead(col, 1, '') over (order by id) next_col
from tablename
)
where col <> next_col
参见demo。
结果:
| col |
| --- |
| A |
| B |
| A |
我有按顺序重复的数据..
A
A
A
B
B
B
A
A
A
我需要这样分组
A
B
A
使用 sqlite 执行此操作的最佳方法是什么?
假设您有一个定义行顺序的列,例如 id
,您可以使用 window 函数解决此 gaps-and-island 问题:
select col, count(*) cnt, min(id) first_id, max(id) last_id
from (
select t.*,
row_number() over(order by id) rn1,
row_number() over(partition by col order by id) rn2
from mytable t
) t
group by col, rn1 - rn2
order by min(id)
我在结果集中添加了几列,以提供有关每组内容的更多信息。
如果您定义了定义行顺序的列,例如 id
,您可以使用 window 函数 LEAD()
:
select col
from (
select col, lead(col, 1, '') over (order by id) next_col
from tablename
)
where col <> next_col
参见demo。
结果:
| col |
| --- |
| A |
| B |
| A |