SQL 求连续段的最后一个数及每段的个数

题目来源:https://www.nowcoder.com/discuss/480253?type=all&order=time&pos=&page=1&channel=1009&source_id=search_all

数据

create table test
(
  id int
);

insert into test values 
(1),
(2),
(4),
(5),
(6),
(9),
(10),
(11),
(12)
;

sql

select segment_max, count(id) as `count`
from
(
  select t3.id, min(t2.id) as segment_max
  from test t3 left join
  (
    select id from test t1 where not exists
    (select id from test where id=t1.id+1)
  ) t2
  on t3.id <= t2.id
  group by t3.id
) t4
group by segment_max
;

让我来解释一下吧,先查询每个数据段的最大值

select id from test t1 where not exists
(select id from test where id=t1.id+1);

SQL 求连续段的最后一个数及每段的个数_第1张图片
然后,在原数据上增加一列:

select t3.id, min(t2.id) as segment_max
from test t3 left join
(
  select id from test t1 where not exists
  (select id from test where id=t1.id+1)
) t2
on t3.id <= t2.id
group by t3.id;

SQL 求连续段的最后一个数及每段的个数_第2张图片

接下来就简单了吧,直接聚合计数即可!

你可能感兴趣的:(#,SQL)