如何找到最长的连续结果集?

时间:2017-04-10 06:45:19

标签: sql oracle

SELECT team1, score1, score2, team2, gameDate 
FROM GAMES 
WHERE team1 = 'Tottenham Hotspur' 
   OR team2 = 'Tottenham Hotspur'
ORDER BY gameDate ASC;

此查询返回按游戏日期排序的游戏结果和游戏日期(针对“托特纳姆热刺队”)。

team1                score1  score2   team2                     gameDate 
+-------------------------------------------------------------------------+
Tottenham Hotspur      0     0        Manchester City           2010-08-14
Stoke City             1     2        Tottenham Hotspur         2010-08-21
Tottenham Hotspur      0     1        Wigan Athletic            2010-08-28
West Bromwich Albion   1     1        Tottenham Hotspur         2010-09-11
Tottenham Hotspur      3     1        Wolverhampton Wanderers   2010-09-18
West Ham United        1     0        Tottenham Hotspur         2010-09-25
Tottenham Hotspur      2     1        Aston Villa               2010-10-02
Fulham                 1     2        Tottenham Hotspur         2010-10-16
Tottenham Hotspur      1     1        Everton                   2010-10-23
Manchester United      2     0        Tottenham Hotspur         2010-10-30
Bolton Wanderers       4     2        Tottenham Hotspur         2010-11-06
Tottenham Hotspur      1     1        Sunderland                2010-11-09

如何在这里找到最长的连续输赢结果?

在上面的示例中,最多4次连续游戏(按游戏日期排序)没有绘制结果,我们想要过滤那些游戏

team1                score1  score2   team2                     gameDate 
+-------------------------------------------------------------------------+
Tottenham Hotspur      3     1        Wolverhampton Wanderers   2010-09-18
West Ham United        1     0        Tottenham Hotspur         2010-09-25
Tottenham Hotspur      2     1        Aston Villa               2010-10-02
Fulham                 1     2        Tottenham Hotspur         2010-10-16

2 个答案:

答案 0 :(得分:4)

试试这个:

SELECT tttt.* from (
    SELECT ttt.*, RANK() over(order by res desc, seqcnt desc , grp desc) rnk from (
        SELECT tt.*, count(*) over( partition by grp, res) as seqcnt from (
             SELECT t.*,  ROW_NUMBER() over(order by gameDate) - ROW_NUMBER() over(partition by res order by gameDate) as  grp from (
                SELECT  team1, score1, score2, team2, gameDate, case when score1= score2 then  'D' else 'N' end as res 
                FROM GAMES  WHERE team1 = 'Tottenham Hotspur' OR team2 = 'Tottenham Hotspur'
            ) t
        ) tt
    ) ttt 
) tttt WHERE rnk = 1 order by gameDate

答案 1 :(得分:0)

你可以尝试

SELECT team1, score1, score2, team2, gameDate 
FROM GAMES 
WHERE team1 = 'Tottenham Hotspur' 
   OR team2 = 'Tottenham Hotspur' 
and score1<>score2 
ORDER BY gameDate ASC