SELECT COUNT(m.winner = p.userName) AS wins, YEAR(m.datePlayed) AS year, DATE_FORMAT(m.datePlayed, '%M') AS month, COUNT(*) as games FROM allMatches AS m LEFT JOIN playerUsers AS p ON m.season = p.season AND (m.player1 = p.userName OR m.player2 = p.userName) WHERE p.realName = '$realName' AND m.winner != '' AND m.canceled != '1' GROUP BY YEAR(m.datePlayed), MONTH(m.datePlayed)";
我们加入了2个表:allMatches和playerUsers。 PlayerUser的用户名与给定赛季的allMatches表上的player1或player2(可能还有赢家)相匹配。
我想计算一下比赛的数量(他们所参加的任何比赛)和他们赢得的比赛数量(他们在playerUsers上的用户名在allMatches上匹配赢家)。上面的SQL语句将wins和games都作为相同的数字返回。有没有办法在同一个SQL语句中计算胜利和游戏的数量?
答案 0 :(得分:2)
使用SUM
代替COUNT
来计算获胜次数:
SELECT SUM(m.winner = p.userName) AS wins, ...
它的工作原理是因为布尔表达式的计算结果为0和1,所以SUM
给出表达式为真的行总数。