简体   繁体   中英

sql query using aggregate function inside case

I'm trying to solve #13 on http://www.sqlzoo.net/wiki/The_JOIN_operation

"List every match with the goals scored by each team as shown. This will use "CASE WHEN" which has not been explained in any previous exercises."

Here is what I wrote:

select distinct mdate, team1,
 case 
    when teamid = team1
      count(teamid)
 end as score1, team2,
 case 
    when teamid = team2
     count(teamid) 
 end as score2
from game join goal on id = matchid
group by matchid
order by mdate, matchid, team1, team2;

I am getting this error:

You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'count(teamid) end as score1, team2, case when teamid = tea' at line 4

what is wrong with my code?

you r on wrong track with case condition and using functions..below query give you result..check and learn hope it will help

SELECT  game.mdate, 
        game.team1,
        SUM(CASE WHEN goal.teamid=game.team1 THEN 1 ELSE 0 END) score1, 
        game.team2,
        SUM(CASE WHEN goal.teamid=game.team2 THEN 1 ELSE 0 END) score2
FROM game
INNER JOIN goal 
    ON game.id=goal.matchid
GROUP BY game.mdate, goal.matchid, game.team1, game.team2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM