我得到了这个SELECT。我想计算(或总和?)玩家的黄牌和红牌(只有YellowCard = 1时才计数黄牌,而RedCard = 1时只计算红牌)..此SELECT无法正常工作。它即使有0或NULL也会计数卡。我该如何纠正它?
SELECT Firstname, Lastname, COUNT(YellowCard) AS Yellow, COUNT(RedCard) AS Red, Team.Name
FROM PlayerMatch
Inner join Player On PlayerMatch.PlayerId = Player.PlayerId
INNER JOIN Team ON Player.TeamId = Team.TeamId
INNER JOIN Match ON PlayerMatch.MatchId = Match.MatchId
WHERE(YellowCard = 1 OR RedCard = 1)
GROUP BY Lastname, Firstname, Name
ORDER BY Yellow DESC
答案 0 :(得分:7)
使用SUM()
代替COUNT()
:
SELECT Firstname, Lastname,
SUM(YellowCard) AS Yellow, SUM(RedCard) AS Red, t.Name
FROM PlayerMatch pm Inner join
Player p
On pm.PlayerId = p.PlayerId INNER JOIN
Team t
ON p.TeamId = t.TeamId INNER JOIN
Match m
ON pm.MatchId = m.MatchId
WHERE (YellowCard = 1 OR RedCard = 1)
GROUP BY Lastname, Firstname, Name
ORDER BY Yellow DESC;
这假设YellowCard
和RedCard
的值始终为0或1(或NULL
)。这似乎是一个合理的假设。
如果不是这种情况,请使用CASE
:
SELECT Firstname, Lastname,
SUM(CASE WHEN YellowCard = 1 THEN 1 ELSE 0 END) AS Yellow,
SUM(CASE WHEN RedCard = 1 THEN 1 ELSE 0 END) AS Red,
t.Name
答案 1 :(得分:2)
不,NULL
不计算在内。如果YellowCard
,RedCard
仅采用0,1,NULL
值:
SELECT Firstname, Lastname, COUNT(nullif(YellowCard,0)) AS Yellow, COUNT(nullif(RedCard,0)) AS Red, Team.Name
FROM PlayerMatch
Inner join Player On PlayerMatch.PlayerId = Player.PlayerId
INNER JOIN Team ON Player.TeamId = Team.TeamId
INNER JOIN Match ON PlayerMatch.MatchId = Match.MatchId
WHERE(YellowCard = 1 OR RedCard = 1)
GROUP BY Lastname, Firstname, Name
ORDER BY Yellow DESC
答案 2 :(得分:0)
你不能这样做,因为在SQL中将从group& where子句,所以你的别名还不存在。
您必须使用SQL子查询作为本教程:http://www.dofactory.com/sql/subquery
如果你尝试,这将有效: 选择 * 来自PlayerMatch内部联接...... 在哪里YellowCard(SELECT * FROM yourTable WHERE YellowCard = 1) 和RedCard(SELECT * FROM yourTable WHERE RedCard = 1)...