I have the following data in a Postgres table named orders:
month_year order_id customer_id
2016-04 0001 24662
2016-05 0002 24662
2016-05 0002 24662
2016-07 0003 24662
2016-07 0003 24662
2016-07 0004 24662
2016-07 0004 24662
2016-08 0005 24662
2016-08 0006 24662
2016-08 0007 24662
2016-08 0008 24662
2016-08 0009 24662
2016-08 0010 11372
2016-08 0011 11372
2016-09 0012 24662
2016-10 0013 24662
2016-10 0014 11372
2016-11 0015 24662
2016-11 0016 11372
2016-12 0017 11372
2017-01 0018 11372
2017-01 0019 11372
SQL fiddle at http://sqlfiddle.com/#!17/4efe6/1.
I'd like to be able to count the number of "repeat customers" per month. We can define "repeat" as a customer having EVER placed an order (whether it was last month or years ago).
For example, customer 24662 placed his first order in April 2016. Therefore, in any subsequent month, if customer 24662 places another order, then he will get a 1 count in that month.
I tried with the following:
SELECT
month_year,
COUNT(DISTINCT(customer_id))
FROM
orders
GROUP BY
month_year
HAVING
COUNT(order_id) > 1
Which gives:
month_year repeat_orders
2016-05 1
2016-07 1
2016-08 2
2016-10 2
2016-11 2
2017-01 1
But, because of the GROUP BY, this is only applying the 1 count based on the whether a customer had more than 1 order in a given month, not whether he/she EVER had a previous order.
I'm looking for the latter, and would expect to see the following:
month_year repeat_orders
2016-05 1
2016-07 1
2016-08 1
2016-09 1
2016-10 2
2016-11 2
2016-12 1
2017-01 1
Any assistance would be most appreciated. Thanks!