有没有办法在 presto 中将一列除以列总数?

Is there a way of dividing a column by the column total in presto?

我正在快速设置查询。

我有两列-一列是类别,另一列是数字。

我想按总数设置数字列,同时将不同的类别组合在一起

something like this is what I have in mind

我很确定如何使用“with”结构来实现这一点,但是有没有一种方法可以在同一个 table 中做到这一点?

您可以使用 window functions 来达到这个目的:

WITH data (category, number) AS (
    VALUES
        ('A', 1),
        ('A', 2),
        ('A', 3),
        ('B', 4),
        ('B', 5),
        ('B', 6)
)
SELECT category, number * 1e0 / sum(number) OVER (PARTITION BY category)
FROM data

产生:

 category |        _col1
----------+---------------------
 A        | 0.16666666666666666
 A        |  0.3333333333333333
 A        |                 0.5
 B        | 0.26666666666666666
 B        |  0.3333333333333333
 B        |                 0.4
(6 rows)