[英]SQL - How to get the percentage of 2 sums
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). 我目前正在使用下面的代码,因此收到0(查看随附的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 如果取2个整数
clicks = 3
uploads = 2
Then clicks / uploads
equals 1
- not 1.5
as you expect: 然后, clicks / uploads
等于1
而不是您期望的1.5
:
http://sqlfiddle.com/#!18/0ed4a9/8/0 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: 使用子查询或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. 的* 1.0
是避免整数除法的问题(即, 1/2=0
,而不是1.5
。的NULLIF()
是由零,以避免分裂。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.