Eren :
I have a user table as below;
Column Name Column Datatype Column Description
user_id varchar Unique user id
reg_ts timestamp Registration date
reg_device varchar Device registered
reg_attribution varchar Acquisition type
I am trying to find "On a typical day, what share of registrants are coming from each acquisition source?"
I wrote the code below but not sure how to divide by the total number of records:
select reg_ts as registiration_date,
reg_attribution as acquisition_type,
count(*)
from users
group by 1,2
order by 1 asc
After I run the code above, I get only get the count of each acquisition type for each date. But I need to find the share of registrants are coming from each acquisition type. Can you please help me fix my query?
sticky bit :
You can use a correlated subquery that gets the count for a day (assuming that reg_ts
is a day despite being a timestamp
).
SELECT u1.reg_ts AS registiration_date,
u1.reg_attribution AS acquisition_type,
count(*) / (SELECT count(*)
FROM users u2
WHERE u2.reg_ts = u1.reg_ts) AS share
FROM users u1
GROUP BY u1.reg_ts,
u1.reg_attribution
ORDER BY u1.reg_ts ASC;
Edit:
If you want the ratio in regard to the total number of users rather than users that registered that day just remove the WHERE
clause from the subquery.
SELECT u1.reg_ts AS registiration_date,
u1.reg_attribution AS acquisition_type,
count(*) / (SELECT count(*)
FROM users u2) AS share
FROM users u1
GROUP BY u1.reg_ts,
u1.reg_attribution
ORDER BY u1.reg_ts ASC;
Guess you like
Origin http://43.154.161.224:23101/article/api/json?id=360200&siteId=1