计算值为1的位置

时间:2017-04-03 11:48:16

标签: sql sql-server

我得到了这个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

3 个答案:

答案 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;

这假设YellowCardRedCard的值始终为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不计算在内。如果YellowCardRedCard仅采用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)...