简体   繁体   中英

sql: select counts of two column values grouped by another column and get ratio of two counts

I have a table that contains indiviual ad clicks and ad impressions labeled by country. Something like this:

在此处输入图像描述

What I need is get to find click-through ratio per country ( ad_click count divided by ad_impression count per country).

I can do counts:

SELECT 
    `events_20200918`.`geo`.`country` AS `geo_country`,
    `events_20200918`.`event_name` AS `event_name`,
    count(1) AS `count_of_rows`
FROM `smartsecurity2-fccc6`.`analytics_238757844`.`events_20200918` AS `events_20200918`
WHERE 
    `events_20200918`.`event_name` IN ('S_ad_impression', 'S_ad_click')
GROUP BY
    1,  2 
ORDER BY 
    3 DESC 

which results in the following:

在此处输入图像描述

but how do I add ad_click/ad_impression ratio per country?

If ou want one row per country, with the clickts to impressions ratio, you can use conditional aggregation:

select 
    `geo`.`country` as `geo_country`,
    safe_divide(
        1.0 * countif(`event_name` = 's_ad_click'),
        countif(`event_name` = 's_ad_impression')
    ) as ratio
from `smartsecurity2-fccc6`.`analytics_238757844`.`events_20200918` as `events_20200918`
where `event_name` in ('S_ad_impression', 'S_ad_click')
group by 1

This groups by country, and then divides the number of clicks by the number of impressions. safe_divide() avoids the division by 0 error if a country has clicks but no impressions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM