Forum

Posted by Eberto, Feb. 6, 2022, 10:13 a.m.

Why is my query incorrect in 100. Advertiser ROI question?

My query is giving the right ROI in some advertisers according to the expected solution. I believe that the difference is that the order of the rows is different.
This is my query:
WITH revenue as (
SELECT ad_id, sum(spend) as total
FROM ad_info
group by ad_id
), cost as (
SELECT advertiser_id, ad_id, sum(cost) as total
FROM advertiser
group by 1,2)
SELECT advertiser_id, avg(COALESCE(revenue.total, 0))/sum(cost.total)
FROM revenue
INNER JOIN cost on revenue.ad_id=cost.ad_id
group by 1

Answers

Hi Eberto,
Thanks for your question.
I saw there were two bugs:
1. the revenue should be summed up to compute the total revenue per advertiser, so instead of using AVG, it should be SUM;
2. with INNER JOIN you missed advertisers with no revenue.
Made some small changes to your solution and it worked.
WITH revenue as (
SELECT ad_id, sum(spend) as total
FROM ad_info
group by ad_id
), cost as (
SELECT advertiser_id, ad_id, sum(cost) as total
FROM advertiser
group by 1,2)
SELECT advertiser_id, SUM(COALESCE(revenue.total, 0))/sum(cost.total)
FROM revenue
RIGHT JOIN cost on revenue.ad_id=cost.ad_id
group by 1
Let us know if you have further questions.
Leon
SQLPad user avatar

Leon (949)

Feb. 6, 2022, 10:54 a.m.