如何计算具有特定值的行?

时间:2017-03-29 11:36:32

标签: sql sql-server

我得到了这个SELECT,它显示了匹配的结果,但即使目标= 0,它也会计算目标。如何定义只计算目标等于1的位置?

SELECT 
    B1.Name AS HomeTeam, ISNULL(C1.Goal, 0) AS HomeTeamScore, 
    ISNULL(C2.Goal, 0) AS AwayTeamScore, B2.Name AS AwayTeam
FROM 
    Match A
INNER JOIN 
    Team AS B1 ON A.HomeTeamId = B1.TeamId
INNER JOIN 
    Team AS B2 ON A.AwayTeamId = B2.TeamId
LEFT JOIN 
    (SELECT MatchId, TeamId, COUNT(Goal) AS Goal
     FROM PlayerMatch
     INNER JOIN Players ON Players.PlayerId = PlayerMatch.PlayerId
     GROUP BY MatchId, TeamId) C1 ON A.MatchId = C1.MatchId AND A.HomeTeamId = C1.TeamId
LEFT JOIN 
    (SELECT MatchId, TeamId, COUNT(Goal) AS Goal
     FROM PlayerMatch 
     INNER JOIN Players ON Players.PlayerId = PlayerMatch.PlayerId
     GROUP BY MatchId, TeamId) C2 ON A.MatchId = C2.MatchId AND A.AwayTeamId = C2.TeamId

4 个答案:

答案 0 :(得分:2)

您可以添加WHERE条件where goal <> 0或使用条件count()

COUNT(case when Goal <> 0 then 1 else 0 end) AS Goal

使你的子查询像

 LEFT JOIN (SELECT MatchId, TeamId, COUNT(Goal) AS Goal
            FROM PlayerMatch
            INNER JOIN Players ON Players.PlayerId = PlayerMatch.PlayerId
            WHERE Goal <> 0 ---Here
            GROUP BY MatchId, TeamId) C1 

答案 1 :(得分:2)

使用此功能。

LEFT JOIN (SELECT MatchId, TeamId, COUNT(Goal) AS Goal
        FROM PlayerMatch
        INNER JOIN Players ON Players.PlayerId = PlayerMatch.PlayerId
        GROUP BY MatchId, TeamId) C1 ON A.MatchId = C1.MatchId AND A.HomeTeamId =C1.TeamId 
        Having COUNT(Goal) = 1

答案 2 :(得分:1)

如果目标

中的值为0或1,则很简单
sum(Goal) AS Goal

OR

 COUNT(case when Goal <> 0 then 1 end) AS Goal

答案 3 :(得分:0)

不要忘记COUNT()会计算所有非空值,而不仅仅是值&gt; 0

结果,使用:

isImageAdded

或缩写为:

COUNT(CASE WHEN goal > 0 THEN 1 ELSE NULL END)