The table nba records the name and year of the NBA (team VARCHAR2(10), y NUMBER(4)) winning team:
TEAM Y
-------------------------
Pistons 1990
Bull 1991
Bull 1992
Bull 1993
Rocket 1994
Rocket 1995
Bull 1996
Bull 1997
Bull 1998
Spurs 1999
Lakers 2000
Lakers 2001
Lakers 2002
Spurs 2003
Pistons 2004
Spurs 2005
Heat 2006
Spurs 2007
Celtic 2008
Lakers 2009
Lakers 2010
Please write an SQL statement to find out who has won the championship consecutively during this period, and what is the start and end time of the consecutive years,
The result is as follows:
TEAM B E
------------------------------ ---------
Bull 1991 1993
Rocket 1994 1995
Bull 1996 1998
Lakers 2000 2002
Lakers 2009 2010
Answer:
SELECT MAX(nn.team) team,MIN(nn.y) Beginy,MAX(nn.y)+1 Endy FROM (SELECT n2.team,n2.y,ROWNUM,n2.y-ROWNUM FROM (SELECT * FROM nba) n1 INNER JOIN (SELECT * FROM nba) n2 ON n1.team=n2.team WHERE n1.y=n2.y+1) nn GROUP BY (nn.y-ROWNUM) ORDER BY Beginy;
1. Query the teams that have won awards for two consecutive years through their own query. For the convenience of understanding, two pseudo-columns are added to represent the row number and the year when the team started winning the award.
SELECT n2.team,n2.y,ROWNUM,n2.y-ROWNUM FROM (SELECT * FROM nba) n1 INNER JOIN (SELECT * FROM nba) n2 ON n1.team=n2.team WHERE n1.y=n2.y+1
search result
2. Use the above results as a subquery, sort by the year of the award, and the last consecutive award year is MAX(nn.y)+1
SELECT MAX(nn.team) team,MIN(nn.y) Beginy,MAX(nn.y)+1 Endy FROM (SELECT n2.team,n2.y,ROWNUM,n2.y-ROWNUM FROM (SELECT * FROM nba) n1 INNER JOIN (SELECT * FROM nba) n2 ON n1.team=n2.team WHERE n1.y=n2.y+1) nn GROUP BY (nn.y-ROWNUM) ORDER BY Beginy;
search result