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
This is complicated, but I would try the following.
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
I want to add some other suggestion. Because your current problem have some contradictions and may not have a proper answer with current rules.
D, A, B, C
but then last two can't be enforce.
inside conference win
. So you could count how many win each team have inside this group as a way of order. My guess is you should analyze the restrictions. Maybe the order of rules is different and you can reduce THIS problem to one where only two team are tie.