I have an SQL query like the following:
SELECT store_id, SUM(quantity_sold) AS count
FROM sales_table
WHERE store_id IN ('Store1', 'Store2', 'Store3')
GROUP BY store_id;
This returns a row for each store that has rows in sales_table, but does not return a row for those that do not. What I want is one row per store, with a 0 for count if it has no records.
How can I do this, assuming that I do not have access to a stores table?
If you do have a
storestable, then simply do an outer join to that one instead of “making one up” using the common table expression (with ..).This can also be written without the CTE (common table expression):
(But I find the CTE version easier to understand)