Table create script:
CREATE TABLE data (account_id int, cust_status varchar(25), amount int, date date);
INSERT INTO data VALUES
('1', 'first_login', '1000', '01/01/2021'),
('1', 'sale', '500', '28/01/2021'),
('2', 'first_login', '2000', '07/03/2021'),
('3', 'first_login', '1000', '01/06/2021'),
('3', 'sale', '2000', '05/08/2021'),
('4', 'first_login', '5000', '18/06/2021'),
('4', 'sale', '3000', '18/09/2021'),
('5', 'first_login', '5000', '02/06/2021'),
('6', 'first_login', '2000', '11/06/2021'),
('7', 'first_login', '1000', '22/06/2021'),
('8', 'first_login', '3000', '29/06/2021');
Here is data from that table:
acc_id | cust_status | amount | date |
---|---|---|---|
1 | first_login | 1000 | 01/01/2021 |
1 | sale | 500 | 28/01/2021 |
2 | first_login | 2000 | 07/03/2021 |
3 | first_login | 1000 | 01/06/2021 |
3 | sale | 2000 | 05/08/2021 |
4 | first_login | 5000 | 18/06/2021 |
4 | sale | 3000 | 18/09/2021 |
5 | first_login | 5000 | 02/06/2021 |
6 | first_login | 2000 | 11/06/2021 |
7 | first_login | 1000 | 22/06/2021 |
8 | first_login | 3000 | 29/06/2021 |
I need to calculate what is the conversion rate for customer every month.
Total account has created as first_login
in month and how many of them converted into sale later.
I tried to calculate the result based on the formulas but stuck at how to make self/inner join in order to bring desired result.
Result should look like:
close rate | close vol rate | month |
---|---|---|
100% | 50% | January |
0 | 0 | March |
33.3% | 29.41% | June |
As in June there are 6 account created as first_login
and only 2 of them later converted into sale.
- conversion close rate = count(sale)/count(first_login)*100
- conversion close vol rate = sum(sale)/sum(first_login)*100
Thank you in advance 🙂
2
Answers
I imported your data to DBFIDDLE and here is a working demo
The following query shall get you the output in Expected format.
The query with your fomulae will throw a division by zero error if there are no first_login events for a particular month. In order to handle this, I have used the
NULLIF
function to return a null value instead of zero if the denominator is zero.This gives same output as manually calculated output :
Try to do a left join and aggregate using filters with sum and count functions as the following:
The
nullif
is used to avoid division by zero, andcoalesce
is used to replace nulls by zero.Demo