'SQL statement - one result to be divided with another
I'm very new to this SQL world so it might be a dumb question.
I have this table "page_load" with, amongst others, the columns "page_title","user_id" and "utm_source". I can view the total of distinct "user_id" with filter on "page_title" with this simple code:
SELECT count(distinct "page_load"."user_id")
FROM "page_load"
WHERE "page_title" = 'Discover'
And I can view another filter with this one:
SELECT count(distinct "page_load"."user_id")
FROM "page_load"
WHERE "utm_source" = 'recommend"
Well, can I get the second result to be divided by the first?
This way I can get the percentage of the second based on the first on a SQL question.
Solution 1:[1]
Use a ratio with conditional aggregation:
SELECT 100.0 * COUNT(DISTINCT CASE WHEN utm_source = 'recommend' THEN user_id END) /
COUNT(DISTINCT CASE WHEN page_title = 'Discover' THEN user_id END)
FROM page_load
WHERE utm_source = 'recommend' OR page_title = 'Discover';
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
