I am trying to get the CTR from uploads to clicks. How would I be able to get this percentage?
I am currently using the code below and I receive 0 as a result (view attached img).
SELECT geo_country, [created_at:date:aggregation] AS day,
SUM(case when name = 'adclick' then 1 else 0 end) as clicks,
SUM(case when name = 'camera_upload_image' then 1 else 0 end) as uploads,
CONVERT(DECIMAL(10,2), clicks / NULLIF(uploads, 0)) As CTR
FROM events
Results:
What you're running into is integer division.
If you take 2 integers
clicks = 3
uploads = 2
Then clicks / uploads
equals 1
- not 1.5
as you expect:
http://sqlfiddle.com/#!18/0ed4a9/8/0
As you can see from that fiddle, the way around this is to ensure that your values are cast/converted to floating point numbers before doing the division.
Convert your results to decimal also:
SELECT geo_country, [created_at:date:aggregation] AS day,
SUM(case when name = 'adclick' then 1 else 0 end) as clicks,
SUM(case when name = 'camera_upload_image' then 1 else 0 end) as uploads,
CONVERT(DECIMAL(10,2), CONVERT(DECIMAL(10,2),clicks) / NULLIF(CONVERT(DECIMAL(10,2),uploads), 0)) As CTR
FROM events
Use a subquery or CTE:
SELECT c.*, clicks * 1.0 / NULLIF(uploads, 0) as ratio
FROM (SELECT geo_country, [created_at:date:aggregation] AS day,
SUM(case when name = 'adclick' then 1 else 0 end) as clicks,
SUM(case when name = 'camera_upload_image' then 1 else 0 end) as uploads
FROM events
GROUP BY geo_country, [created_at:date:aggregation]
) c;
The * 1.0
is to avoid integer division issues (ie 1/2=0
rather than 1.5
. The NULLIF()
is to avoid division by zero.
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.