如何使用Hive/Presto查找列的百分比

Uts*_*hah 3 hive presto

假设我有一张表格如下:

Reason          | Duration
Eating              40
Drinking            60
Everything Else     100
Run Code Online (Sandbox Code Playgroud)

我如何获得这样的表格:

Reason          | Duration | Duration Percent
Eating              40             20
Drinking            60             30
Everything Else     100            50
Run Code Online (Sandbox Code Playgroud)

Dav*_*ips 10

您可以使用窗口函数来计算总数:

SELECT reason, duration, (duration * 100.0) / sum(duration) OVER () pct
FROM (
  VALUES
    ('eating', 40),
    ('drinking', 60),
    ('other', 100)
) AS t (reason, duration)
Run Code Online (Sandbox Code Playgroud)

请注意,Presto(根据SQL标准)执行整数除法,因此必须将其中一个值转换为double或decimal(否则结果将为零).

  reason  | duration | pct  
----------+----------+------
 eating   |       40 | 20.0 
 drinking |       60 | 30.0 
 other    |      100 | 50.0 
(3 rows)
Run Code Online (Sandbox Code Playgroud)