Question

I've got two tables in a SQLite database, and I'm attempting to calculate the count of the routes by rating. It works, but doesn't return 0 for when there isn't a route with that rating. An example rating would be 8, or 11b, or V3.

The query I'm using right now is:

select routes.rating, count(routes.rating) from routes 
left join orderkeys on routes.rating = orderkeys.rating
group by routes.rating
order by orderkeys.key

This doesn't return 0 for the ratings that don't have any routes for them, though. The output I get is:

10d|3
7|3
8|2
9|9
10a|5
10b|4
10c|2
11a|3
12b|1
V0|5
V1|7
V2|5
V3|8
V4|3
V5|1
V6|2
V7|3
V8|2
V9|1

What I expect to get is:

7|3
8|2
9|9
10a|5
10b|4
10c|2
10d|3
11a|3
11b|0
11c|0
11d|0
12a|0
12b|1
12c|0
12d|0
V0|5
V1|7
V2|5
V3|8
V4|3
V5|1
V6|2
V7|3
V8|2
V9|1

Here's the schema:

CREATE TABLE routes (
    id integer PRIMARY KEY,
    type text, rating text, 
    rope integer, 
    name text, 
    date text, 
    setter text, 
    color_1 text, 
    color_2 text, 
    special_base text, 
    blurb text, 
    updater text
);
CREATE TABLE orderkeys (
    rating TEXT,
    key INTEGER PRIMARY KEY
);
Was it helpful?

Solution

A left join returns all records from the left table, but what you want is all ratings, i.e., all records from the orderkeys table:

SELECT orderkeys.rating,
       COUNT(routes.id)
FROM orderkeys
LEFT JOIN routes USING (rating)
GROUP BY orderkeys.rating
ORDER BY orderkeys.key

OTHER TIPS

Try this. I do not like join quite much but it is quite useful when there are a lot of tables:

select routes.rating, count(routes.rating) from routes, rating 
where routes.rating = orderkeys.rating
group by routes.rating
order by orderkeys.key
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top