I'm getting hung up trying to count records from one table based upon the results of a query. My table looks like this:
parent_id | site_id | description
-----------------------------------
A1 1 FL
A1 2 NJ
A1 A1 Company_A
First I created a query to give me the company name on the same row as the state (description). My initial query is:
SELECT master.description, sites.description, sites.site_id
FROM sites sites
INNER JOIN sites master
ON sites.parent_id = master.site_id
Which results in:
Company_A FL 1
Company_A DE 2
So far so good. What I want to do, though, is count the number of orders from the ORDERS table for each site_id, even where the number of orders are 0.
I'm stumped on how to count from the ORDERS table based on the results of my query? Any help on this join would be appreciated.
UPDATE: Almost there! Here's what is working:
SELECT master.description, sites.description, count(order_id) orderCount
FROM sites sites
INNER JOIN sites master
ON sites.parent_id = master.site_id
LEFT JOIN orders o
ON sites.site_id = o.site_id
WHERE sites.site_type = 3
GROUP BY master.description, sites.description, sites.site_id
ORDER BY master.description
The only issue I have left is if I add a date range I get the correct results, but any sites with ZERO orders for that period are not shown. So if I add:
WHERE sites.site_type = 3 AND o.order_date > '2015-10'
I get the correct result but only for sites with orders during that period. What am I missing?
orderstable?