I am trying to find the best way to accomplish the following.
- Get the beginning customer count, which carries from the previous day
- Get New Customer count
- Get the number of Customers who have not come in since the prior month
- Get the number of Customers who have come back after lapsing
- Get the number of total customers
The following example
Customer ID | Store ID | Date | Amount |
---|---|---|---|
1 | 1 | 1/2/22 | 1.00 |
2 | 2 | 1/2/22 | 2.00 |
1 | 1 | 2/2/22 | 1.00 |
3 | 2 | 3/2/22 | 1.00 |
2 | 2 | 3/2/22 | 1.00 |
1 | 1 | 3/2/22 | 1.00 |
1 | 1 | 4/2/22 | 1.00 |
4 | 1 | 4/2/22 | 1.00 |
2 | 2 | 4/2/22 | 1.00 |
The result would be
Date | Store | Beginning | New | Dropped | Returned | Total |
---|---|---|---|---|---|---|
1/2/22 | 1 | 0 | 1 | 0 | 0 | 1 |
1/2/22 | 2 | 0 | 1 | 0 | 0 | 1 |
2/2/22 | 1 | 1 | 0 | 0 | 0 | 1 |
2/2/22 | 2 | 1 | 0 | 1 | 0 | 0 |
3/2/22 | 1 | 1 | 0 | 0 | 0 | 1 |
3/2/22 | 2 | 0 | 1 | 0 | 1 | 2 |
4/2/22 | 1 | 1 | 1 | 0 | 0 | 2 |
4/2/22 | 2 | 2 | 0 | 1 | 0 | 1 |
I kind of have a query, but it's not getting the right results
WITH customerset AS (
SELECT
location_id,
date,
array_agg(DISTINCT customer_id
ORDER BY customer_id ASC)
AS customer_ids
FROM customer_orders
GROUP BY
location_id,
date
)
SELECT
cset.location_id,
cset.date,
array_length(cset2.customer_ids, 1) AS beginning,
array_length((past2.customer_ids - cset.customer_ids), 1) AS dropped,
array_length((cset.customer_ids - past2.customer_ids), 1) AS returned
FROM
(
SELECT
ords.location_id,
ords.date,
array_agg(DISTINCT ords.customer_id
ORDER BY ords.customer_id ASC)
AS customers_id
FROM customer_orders ords
GROUP BY
ords.location_id,
ords.date
) cset
JOIN
customerset cset2
ON cset.date - '1 month'::interval = cset2.date
AND cset2.location_id = cset.location_id
GROUP BY
cset.location_id,
cset.date,
cset2.customer_ids,
cset.customer_ids
ORDER BY
cset.date ASC