SQL: 添加行值并在新列中显示

SQL: Add the row values and display in new column

我有 table t1 按 tasteRating

订购
    Fruit | tasteRating|Cost 
    -----------------------
    Apple |  99       | 1  
    Banana|  87       | 2  
    Cherry|  63       | 5 

我想要t2

    Fruit | Cost | Total Cost
    -------------------------
    Apple |   1  | 1
    Banana|   2  | 3
    Cherry|   5  | 8

有没有办法根据成本值在 SQL 中动态生成总成本? 在 Redshift 上执行此操作。 谢谢

这样的 运行 总和,可以使用 window 函数在 modern DBMS 中轻松完成:

select col_1,
       sum(col_1) over (order by taste_rating desc) as col_2
from the_table;

但是请注意,没有 order by 的 运行 总和没有意义。因此,您必须包含一个定义行顺序的列。

SQLFiddle: http://sqlfiddle.com/#!15/166b9/1

编辑:(作者:戈登)

RedShift 对 Window 函数有奇怪的限制。出于某种原因,它需要 rows between 语法:

sum(col_1) over (order by taste_rating desc
                 rows between unbounded preceding and current row
                ) as col_2

我不知道为什么会有这个要求。它不是 ANSI 所要求的(尽管它是受支​​持的)并且它不是 Postgres(Redshift 的基础数据库)中的限制。