SQL-如何获得2个总和的百分比

时间:2019-06-25 15:41:55

标签: sql

我正在尝试将点击率从上传到点击。我将如何获得这个百分比?

我目前正在使用下面的代码,因此我收到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

3 个答案:

答案 0 :(得分:1)

您遇到的是整数除法。

如果取2个整数

clicks = 3 
uploads = 2

然后clicks / uploads等于1-不等于您期望的1.5

http://sqlfiddle.com/#!18/0ed4a9/8/0

正如您从小提琴中看到的那样,解决该问题的方法是确保在进行除法运算之前将您的值强制转换/转换为浮点数。

答案 1 :(得分:0)

还将您的结果转换为十进制:

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

答案 2 :(得分:0)

使用子查询或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;

* 1.0避免整数除法问题(即1/2=0而不是1.5NULLIF()避免除零。