I am a bit confused about why I got a different answer by using SUM(column = "xxx") and COUNT() with WHERE. Their logic looks the same to me...
In case you guys want some background of the problem:
My query that got the wrong answer:
WITH clicked AS(
SELECT ad_id, COUNT(action) AS c_cnt
FROM Ads
WHERE action = "clicked"
GROUP BY ad_id),
viewed AS(
SELECT ad_id, COUNT(action) AS v_cnt
FROM Ads
WHERE action = "Viewed"
GROUP BY ad_id),
total AS(
SELECT ad_id, c_cnt/(c_cnt+v_cnt)*100 AS ctr
FROM clicked
JOIN viewed
USING(ad_id)
GROUP BY ad_id)
SELECT DISTINCT ad_id, IFNULL(ROUND(ctr,2),0) AS ctr
FROM Ads
LEFT JOIN total
USING(ad_id)
ORDER BY 2 DESC, 1 ASC
My query that got the right answer:
WITH clicked AS(
SELECT ad_id, SUM(action = "Clicked") AS c_cnt
FROM Ads
GROUP BY ad_id),
viewed AS(
SELECT ad_id, SUM(action = "Viewed") AS v_cnt
FROM Ads
GROUP BY ad_id),
total AS(
SELECT ad_id, c_cnt/(c_cnt+v_cnt)*100 AS ctr
FROM clicked
JOIN viewed
USING(ad_id)
GROUP BY ad_id)
SELECT DISTINCT ad_id, IFNULL(ROUND(ctr,2),0) AS ctr
FROM Ads
LEFT JOIN total
USING(ad_id)
ORDER BY 2 DESC, 1 ASC
The only different part is the part I highlighted in yellow:
The picture is the test case that my first query did not pass.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…