问题描述
我有顺序重复的数据。
A
A
A
B
B
B
A
A
A
我需要像这样将它们分组
A
B
A
解决方法
假设您有一列定义行的顺序的列,例如id
,则可以使用窗口函数来解决这个“孤岛”问题:
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
,则可以使用窗口函数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 |