如何计算雅典娜(Presto)的总百分比?

时间:2020-07-19 06:25:03

标签: sql presto amazon-athena

给出一个表,其中包含诸如:

Date, Type

我正在运行以下SQL:

SELECT Type, count(*) as CountPerType
FROM myTable
WHERE Date between 20200101 and 20200131
GROUP BY count(*)

我想要一个额外的列Percentage,其中将有100.0 * CountPerType / SUM(CountPerType)。在PrestoDB(为Amazon Athena提供支持)中最有效的方法是什么?

2 个答案:

答案 0 :(得分:2)

我将编写不带子查询的查询。您可以混合使用窗口函数和聚合函数:

hashCode

我不知道性能是否与使用子查询的版本不同(这应该至少一样好)。但是查询绝对简单。

答案 1 :(得分:1)

您可以使用窗口功能来实现。您应该始终对未汇总的字段进行分组。

select
    Type,
    CountPerType,
    100.0 * CountPerType/sum(CountPerType) over () as columnName
from
(
    SELECT 
        Type, 
        count(*) as CountPerType
    FROM myTable
    WHERE Date between 20200101 and 20200131
    GROUP BY 
        Type
) subq