I’m using the below query to pull back the total product price for a date range, however on the days that no sales where made, i’d like to still show the date but with a value of 0.
I’ve created a calendar table with a large date range, but haven’t been able to work out the best way to do it, everything i’m doing just misses out the days with no sales.
Below is the query i’m using (Without the calendar table):
SELECT DATE_FORMAT(b.purchase_date, '%d %b %Y') as date, sum(price) as price
FROM order_products a
INNER JOIN order_saved b
ON a.order_id = b.id
WHERE b.purchase_date
BETWEEN '2011-09-16 23:59' AND '2011-10-16 23:59'
AND b.status > 2
AND a.usr_id = 'XXXX'
GROUP BY DAY(b.purchase_date)
ORDER BY b.purchase_date ASC
The calendar table i’ve tried with just contains a list of date ranges starting from 2010-01-01 up to 2014-12-30 (calendar.date is the table.row)
Any help would be amazing.
Thanks!
You need an outer join on the calendar table. Something like
You’ll get better answers if you post the DDL (
CREATE TABLE) statements, and minimalINSERTstatements that give us enough data to actually test our answers. (Edit your question and paste the DDL and INSERT statements.)