Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Whats wrong with my query with CASE statement

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's my query:

SELECT game.mdate, game.team1, 
SUM(CASE WHEN goal.teamid = game.team1 THEN 1 ELSE 0 END) AS score1,
game.team2,
SUM(CASE WHEN goal.teamid = game.team2 THEN 1 ELSE 0 END) AS score2

FROM game INNER JOIN goal ON matchid = id
GROUP BY game.id
ORDER BY mdate,matchid,team1,team2

I get the result "Too few rows". I don't understand what part I got wrong.

like image 271
Programmerboi Avatar asked Apr 15 '14 11:04

Programmerboi


People also ask

Can we use CASE statement in SELECT query?

We can use a Case statement in select queries along with Where, Order By, and Group By clause. It can be used in the Insert statement as well. In this article, we would explore the CASE statement and its various use cases.

Where do I put CASE statement in SQL query?

The CASE statement always goes in the SELECT clause. CASE must include the following components: WHEN , THEN , and END . ELSE is an optional component. You can make any conditional statement using any conditional operator (like WHERE ) between WHEN and THEN .

How do you make a case insensitive query?

SQL Case insensitivity is to use the query statements and the keywords tables and columns by specifying them in capital or small letters of alphabets. SQL keywords are by default set to case insensitive that means that the keywords are allowed to be used in lower or upper case.

Can we use CASE statement in update query?

CASE statement works like IF-THEN-ELSE statement. I have SQL server Table in which there is column that I wanted to update according to a existing column value that is present in current row. In this scenario, we can use CASE expression. CASE expression is used for selecting or setting a new value from input values.


1 Answers

An INNER JOIN only returns games where there have been goals, i.e. matches between the goal and game table.

What you need is a LEFT JOIN. You need all the rows from your first table, game but they don't need to match all the rows in goal, as per the 0-0 comment I made on your question:

SELECT game.mdate, game.team1, 
SUM(CASE WHEN goal.teamid = game.team1 THEN 1 ELSE 0 END) AS score1,
game.team2,
SUM(CASE WHEN goal.teamid = game.team2 THEN 1 ELSE 0 END) AS score2

FROM game LEFT JOIN goal ON matchid = id
GROUP BY game.id,game.mdate, game.team1, game.team2 
ORDER BY mdate,matchid,team1,team2

This returns the 0-0 result between Portugal and Spain on 27th June, which your initial answer missed out.

like image 113
mjsqu Avatar answered Sep 30 '22 13:09

mjsqu