面试题sql语句,帮小弟看看
TEAM (varchar2) Y(int)
---------- ---------------------------------------
公牛 1992
公牛 1993
火箭 1994
火箭 1995
公牛 1996
公牛 1997
公牛 1998
马刺 1999
湖人 2000
湖人 2001
湖人 2002
马刺 2003
活塞 2004
马刺 2005
热火 2006
马刺 2007
凯尔特人 2008
湖人 2009
湖人 2010
写一段sql语句,要求查出那个球队是连续两年以上夺冠的(包含2年),显示夺冠的开始和结束时间,显示效果如下:
TEAM START_HM END_HM
---------- ---------- ----------
公牛 1996 1998
火箭 1994 1995
公牛 1992 1993
湖人 2000 2002
湖人 2009 2010
[解决办法]
顺序自己排,
SQL> WITH t AS ( 2 SELECT '公牛' team,1992 y FROM DUAL UNION ALL 3 SELECT '公牛' team,1993 y FROM DUAL UNION ALL 4 SELECT '火箭' team,1994 y FROM DUAL UNION ALL 5 SELECT '火箭' team,1995 y FROM DUAL UNION ALL 6 SELECT '公牛' team,1996 y FROM DUAL UNION ALL 7 SELECT '公牛' team,1997 y FROM DUAL UNION ALL 8 SELECT '公牛' team,1998 y FROM DUAL UNION ALL 9 SELECT 'ma刺' team,1999 y FROM DUAL UNION ALL 10 SELECT '湖人' team,2000 y FROM DUAL UNION ALL 11 SELECT '湖人' team,2001 y FROM DUAL UNION ALL 12 SELECT '湖人' team,2002 y FROM DUAL UNION ALL 13 SELECT 'ma刺' team,2003 y FROM DUAL UNION ALL 14 SELECT '活塞' team,2004 y FROM DUAL UNION ALL 15 SELECT 'ma刺' team,2005 y FROM DUAL UNION ALL 16 SELECT 're火' team,2006 y FROM DUAL UNION ALL 17 SELECT 'ma刺' team,2007 y FROM DUAL UNION ALL 18 SELECT 'kaier特人' team,2008 y FROM DUAL UNION ALL 19 SELECT '湖人' team,2009 y FROM DUAL UNION ALL 20 SELECT '湖人' team,2010 y FROM DUAL 21 ) 22 SELECT t2.team, 23 MIN(t2.y) start_hm, 24 MAX(t2.y) end_hm 25 FROM (SELECT t.team, 26 t.y, 27 t.y - ROW_NUMBER() OVER(PARTITION BY t.team ORDER BY t.y) y1 28 FROM t) t2 29 GROUP BY t2.team, 30 t2.y1 31 HAVING COUNT(*) > 1 32 ;TEAM START_HM END_HM----------- ---------- ----------公牛 1996 1998湖人 2000 2002火箭 1994 1995湖人 2009 2010公牛 1992 1993