I am stuck on implementing a left join on dates for each individual customer.
I have a table which stores customer purchases:
SELECT purchase_date, customer
FROM purchases
I would like to create a similar table however one that includes ALL dates and not just purchase dates, for example:
SELECT date, customer, purchase_made
Where purchase_made
is a BOOLEAN
column. I understand that I need to use a LEFT JOIN
however I am stuck at making sure that EACH customer has a full set of dates. For example if no customers made a purchase on 2016-01-01
, and there are 2000 customers in the database, then 2000 rows of 2016-01-01
should be added (with each row attributed to a customer).
So far I've tried:
WITH dates AS (
SELECT GENERATE_SERIES('2016-01-01'::TIMESTAMP, '2016-01-15'::TIMESTAMP, '1 day'::INTERVAL) AS date
),
SELECT date, customer
FROM purchases
LEFT JOIN dates ON purchases.date=dates.date;
How to implement the BOOLEAN
column?
Also is it possible to add the date rows only AFTER a customers first purchase? So for example only insert 2016-01-01
for customers who made a purchase prior to 2016-01-01
.
Best Answer
To follow on from my comment. I'd recommend a date table.
Sample Customer Purchase Data
Sample Date Table
You could cross join the list of dates to then get a full list of all customers and all dates. Then join to the actual sales data to return the Boolean value you're after.
Results would look like this
If you were to do this then your date table would obviously be much wider than the week example I've done. You could then just use date parameters to restrict to the date range you're after. Something like this;
Which would give these results