如何计算 Athena (Presto) 中总计的百分比?

noa*_*mtm 3 sql presto amazon-athena

给定一个包含以下列的表:

Date, Type
Run Code Online (Sandbox Code Playgroud)

我正在运行以下 SQL:

SELECT Type, count(*) as CountPerType
FROM myTable
WHERE Date between 20200101 and 20200131
GROUP BY count(*)
Run Code Online (Sandbox Code Playgroud)

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

Gor*_*off 10

我会编写没有子查询的查询。您可以混合窗口函数和聚合函数:

SELECT Type,  COUNT(*) as CountPerType,
       COUNT(*) * 100.0 / SUM(COUNT(*)) OVER () as percentage
FROM t
WHERE Date BETWEEN 20200101 AND 20200131
GROUP BY Type;
Run Code Online (Sandbox Code Playgroud)

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