假设我有一张表格如下:
Reason | Duration
Eating 40
Drinking 60
Everything Else 100
如何获得这样的表:
Reason | Duration | Duration Percent
Eating 40 20
Drinking 60 30
Everything Else 100 50
答案 0 :(得分:6)
您可以使用window function计算总数:
SELECT reason, duration, (duration * 100.0) / sum(duration) OVER () pct
FROM (
VALUES
('eating', 40),
('drinking', 60),
('other', 100)
) AS t (reason, duration)
请注意,Presto(根据SQL标准)执行整数除法,因此必须将其中一个值转换为double或decimal(否则结果将为零)。
reason | duration | pct
----------+----------+------
eating | 40 | 20.0
drinking | 60 | 30.0
other | 100 | 50.0
(3 rows)