![](/img/trans.png)
[英]Running total percentage per record over total sum. Presto/Athena/SQL
[英]How to calculate percentage of total in Athena (Presto)?
給定一個包含以下列的表:
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 提供支持)中最有效的方法是什么?
我會編寫沒有子查詢的查詢。 您可以混合使用 window 函數和聚合函數:
SELECT Type, COUNT(*) as CountPerType,
COUNT(*) * 100.0 / SUM(COUNT(*)) OVER () as percentage
FROM t
WHERE Date BETWEEN 20200101 AND 20200131
GROUP BY Type;
我不知道性能是否與使用子查詢的版本不同(這應該至少一樣好)。 但是查詢肯定更簡單。
您可以使用 window 功能來實現這一點。 您應該始終對非聚合字段進行分組。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.