1

I got this SELECT, it shows result of match, but it count Goals even if Goal = 0. How can I define to count only where goals is equal to 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
2
  • What is the data type of goal? Is it an int or bit? Can it only have the values 1 and 0? Or does it sometimes contain 3, 4, etc? Commented Mar 29, 2017 at 11:44
  • Sample data and desired results would help as well. Commented Mar 29, 2017 at 11:46

4 Answers 4

2

You can include a WHERE condition saying where goal <> 0 or use conditional count() like

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

Make your subquery like

 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 
Sign up to request clarification or add additional context in comments.

2 Comments

0 also take as a count 1
may be it will work COUNT(case when Goal <> 0 then 1 end) AS Goal
2

Use this.

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

Comments

1

simple if you have value 0 or 1 in Goal

sum(Goal) AS Goal

OR

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

1 Comment

I think the OP intends SUM().
0

Don't forget that COUNT() counts all non-null values, not just values > 0.

As a result, use:

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

or shortened to:

COUNT(CASE WHEN GOAL > 0 THEN 1 END)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.