測試表:
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;
來源
2010-06-22 14:32:53
Don
這應該是'UNION ALL'(如果約翰在兩場比賽中得分3,它只會計算一次) – Quassnoi 2010-06-22 14:31:19
@Quassnoi,修正了,謝謝! – 2010-06-22 14:33:27