我试图解决这个问题,我有两名玩家拥有游戏分数。查询应返回玩家的图表以及游戏数量,如果得分为3:0或0:3则得分为3的玩家获得3分,否则任何获胜为2分
我的表:
player1 player2 player1score player2score
------- ------- ------------- ------------
john lee 3 0
maria andy 1 3
andy john 1 3
所需的表应该是这样的:
players gamesplayed points
------- ----------- ------
john 2 5
andy 2 2
maria 1 0
lee 1 0
我有这个问题:
SELECT DISTINCT players, count(*) gamesplayed
FROM (
SELECT player1 AS players
FROM table
UNION
SELECT player2 AS players
FROM table
) players
但是上面的查询会在gamesplayed
中单独返回所有玩家的计数,而不是单独返回。
有人能看到问题吗?我也不确定是否热门实施了points
列。
非常感谢
答案 0 :(得分:2)
现在我认为适合MySQL-Statement,只需将其更改为内联视图,没有mysql环境,如果语法不完全正确,则为pz借口:
SELECT player,
COUNT(player) AS gamesPlayed, SUM(score) score
FROM
(SELECT player1 AS player,
CASE
WHEN player1score - player2score > 2 THEN + 3
WHEN player1score - player2score > 0 THEN +2
ELSE + 0
END as score
FROM playerTable
UNION ALL
SELECT player2 AS player,
CASE
WHEN player2score - player1score > 2 THEN + 3
WHEN player2score - player1score > 0 THEN +2
ELSE + 0
END AS score
FROM playerTable)
AS playerSel
Group by player;
答案 1 :(得分:1)
部分困难在于你使用的UNION
会得到不同的值 - 所以如果玩家将游戏作为玩家1玩,而另一游戏作为玩家2玩,那么他只会被计算一次。另外,如果他作为球员1打了两场比赛,他只会被计算一次!
我认为您需要以下内容:
SELECT p1.player, COUNT(*) AS games_played, SUM(p1.player_score) AS total_points
FROM (
SELECT player1 AS player, player1score AS player_score
FROM mytable
UNION ALL
SELECT player2 AS player, player2score AS player_score
FROM mytable
) p1
GROUP BY p1.player;
UNION ALL
会保留所有行,而不是像UNION
那样只获取不同的行。
答案 2 :(得分:1)
在SQL-Server中完成,如果它适用于MySql,则为dunno:
WITH playerSel AS(
SELECT player1 AS player,
CASE
WHEN player1score - player2score > 2 THEN + 3
WHEN player1score - player2score > 0 THEN +2
ELSE + 0
END as score
FROM playerTable
UNION ALL
SELECT player2 AS player,
CASE
WHEN player2score - player1score > 2 THEN + 3
WHEN player2score - player1score > 0 THEN +2
ELSE + 0
END as score
FROM playerTable)
SELECT player,
COUNT(player) AS gamesPlayed, SUM(score) score
FROM playerSel
Group by player;
我检索了以下信息:
和j; 2; 2 约翰; 2; 5 利; 1; 0 玛利亚; 1; 0