Тестовые таблицы:
DECLARE @Table TABLE (Player1Id VARCHAR(17), Player2Id VARCHAR(17), Player1Points INT, Player2Points INT);
INSERT INTO @Table
SELECT 'John', 'Piter', 4, 1 UNION ALL
SELECT 'John', 'Adam', 2, 10 UNION ALL
SELECT 'Piter', 'Adam', 4, 2;
Сумма очков:
WITH CTE (PlayerId, Points) AS (
SELECT Player1Id, Player1Points FROM @Table
UNION ALL
SELECT Player2Id, Player2Points FROM @Table
)
SELECT PlayerId, SUM(Points) FROM CTE GROUP BY PlayerId;
Сумма очков от выигранных игр:
WITH CTE (PlayerId, Points, Won) AS (
SELECT Player1Id, Player1Points, CASE WHEN Player1Points > Player2Points THEN 1 ELSE 0 END FROM @Table
UNION ALL
SELECT Player2Id, Player2Points, CASE WHEN Player2Points > Player1Points THEN 1 ELSE 0 END FROM @Table
)
SELECT PlayerId, SUM(Points) FROM CTE WHERE Won = 1 GROUP BY PlayerId;
Разница:
WITH CTE (PlayerId, Points) AS (
SELECT Player1Id, CASE WHEN Player1Points > Player2Points THEN Player1Points - Player2Points ELSE (Player2Points - Player1Points) * -1 END FROM @Table
UNION ALL
SELECT Player2Id, CASE WHEN Player2Points > Player1Points THEN Player2Points - Player1Points ELSE (Player1Points - Player2Points) * -1 END FROM @Table
)
SELECT PlayerId, SUM(Points) FROM CTE GROUP BY PlayerId;