【问题标题】:Amazon Athena SQL query doesn't yield required result - percentage of totalAmazon Athena SQL 查询未产生所需结果 - 占总数的百分比
【发布时间】:2020-09-02 10:25:31
【问题描述】:

我在 Athena 中尝试过,但我相信这也是一个正确的 SQL 查询。

我有一个带有channel 列的表,我想获得“每月频道的份额等于频道总数中的 1”。所以我考虑过使用条件语句,当它为 1 时放置 1,否则为 0,然后将其相加,这就像计算 1 的出现次数除以一个月的总数。 但它只是给了我零而不是实际的份额。查询有什么问题?

select
  month,
  count(), 
  sum(case when channel = 1 then 1 else 0 end) / count()
from table
where bla bla 
group by 1 order by 1;

【问题讨论】:

  • 在这种情况下,您可能需要使用嵌套查询:“内部”查询生成原始数字,“外部”查询生成摘要。或者,您可能需要JOIN 两个或更多子查询产生的结果。

标签: sql conditional-statements presto amazon-athena


【解决方案1】:

您的问题可能是整数除法。这里有两种方法:

Select month , count(*), sum(case when channel = 1 then 1.0 else 0 end) / count(*)
from table
where bla bla
group by 1
order by 1;

Select month , count(), avg(case when channel = 1 then 1.0 else 0 end)
from table
where bla bla
group by 1
order by 1;

请注意,avg() 是一种更简单的计算方式。

【讨论】:

    【解决方案2】:

    虽然其他提议的解决方案效果很好,但我想提出一个不太冗长的替代方案:

    select month, count(), count_if(channel=1)*1./count()
    from table where
    ... 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-28
      • 2021-02-24
      • 2023-02-18
      • 2017-06-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多