查询获胜球队的连续年份

Question:
查询出在此期间连续获得冠军的有哪些,其连续的年份的起止时间是多少?
创建表格:

create table nba(
team varchar(20),
y int(5));

insert into nba(team,y) values
('活塞',1990),
('公牛',1991),
('公牛',1992),
('公牛',1993),
('火箭',1994),
('火箭',1995),
('公牛',1996),
('公牛',1997),
('公牛',1998),
('马刺',1999),
('湖人',2000),
('湖人',2001),
('湖人',2002),
('马刺',2003),
('活塞',2004),
('马刺',2005),
('热火',2006),
('马刺',2007),
('凯尔特人',2008),
('湖人',2009),
('湖人',2010);

得到如下图所示的结果:


image.png
select min(team) Team,min(y) B,max(y) E
from
(
select min(team) Team,min(y) B,max(y) E
from
        (
         select team,y,
                  if(@pre_team=team,@cur_rank,@cur_rank:=@cur_rank+1) ranking,
                @pre_team:=team fuzhi
     from nba,(select @pre_team:=null,@cur_rank:=0) a
     order by y) t
group by t.ranking
having count(ranking)>=2;

你可能感兴趣的:(查询获胜球队的连续年份)