如何在sql中进行迭代汇总

时间:2009-09-18 14:31:43

标签: sql iteration rollup

嗨我想根据滚动总和(valy)的前一行值和valx的当前行值

进行滚动总和(valx)

valy = previousrow_valy + valx

animal valx valy 
cat    1    1 
cat    3    4 
cat    2    6 
dog    4    4 
dog    6    10 
dog    7    17 
dog    8    25 

1 个答案:

答案 0 :(得分:1)

您应该在这里定义一个订单。

假设您想按somecolumn订购。

OraclePostgreSQL 8.4

SELECT  animal, valx, SUM(valx) OVER (PARTITION BY animal ORDER BY somecolumn) AS valy
FROM    mytable

MySQL

SELECT  animal, valx,
        @valy := CASE WHEN @animal = animal THEN @valy + valx ELSE valx END AS valy,
        @animal := animal
FROM    (
        SELECT  @valy = 0,
                @animal := NULL
        ) vars,
        mytable
ORDER BY
        animal, somecolumn

SQL Server中,这是创建CURSOR效率更高的极少数情况之一。

所有数据库(包括SQL Server)都支持ANSI语法:

SELECT  animal, valx,
        (
        SELECT  SUM(valx)
        FROM    mytable mi
        WHERE   mi.animal = mo.animal
                AND mi.somecolumn <= mo.somecolumn
        ) AS valy
FROM    mytable mo

然而,如果mytable中有很多记录,执行时间会增加为O(n^2)

,则效率不高