Ranking teams equal on points in a pool based on who won the game they played

后端 未结 3 654
没有蜡笔的小新
没有蜡笔的小新 2021-01-21 02:09

I\'m writing an application that calculates the ranking of teams in the pool stages of a rugby competition (Rugby World Cup 2015, but it could apply to many other pool-based

3条回答
  •  忘掉有多难
    2021-01-21 02:31

    This need sql 2012+ using LEAD() and LAG() functions, Also require only two team have same Rank at this moment.

    SCHEMA

    CREATE TABLE Table1
        ([team] varchar(1), [rank] int);
    
    INSERT INTO Table1
        ([team], [rank])
    VALUES
        ('A', 1),('B', 1),('C', 2);
    
    CREATE TABLE Table2
        ([team1] varchar(1), [team2] varchar(1), [win] varchar(1));
    
    INSERT INTO Table2
        ([team1], [team2], [win])
    VALUES
        ('A', 'B', 'B'), ('C', 'A', 'A'),('C', 'B', 'B');
    

    SQL Fiddle Demo

    WITH breakTie AS ( 
        SELECT
            [team],
            [rank],
            LAG([team]) OVER (ORDER BY [rank]) PreviousTeam,
            LEAD([team]) OVER (ORDER BY [rank]) NextTeam,
            LAG([rank]) OVER (ORDER BY [rank]) PreviousRank,
            LEAD([rank]) OVER (ORDER BY [rank]) NextRank
        FROM Table1
    )
    SELECT *, CASE 
           WHEN B.[rank] = B.[NextRank] and B.[team] = T.[win] THEN 1
           WHEN B.[rank] = B.[PreviousRank] and B.[team] = T.[win] THEN 1
           ELSE 0
        END as breakT
    FROM breakTie B
    LEFT JOIN Table2 T
       ON ( B.team = T.team1 or B.team = T.team2)
      AND ( B.NextTeam = T.team1 or B.NextTeam = T.team2)
    ORDER BY 
        [rank],
        CASE 
           WHEN B.[rank] = B.[NextRank] and B.[team] = T.[win] THEN 1
           WHEN B.[rank] = B.[PreviousRank] and B.[team] = T.[win] THEN 1
           ELSE 0
        END
    

提交回复
热议问题