Вопрос

I need to develop a SQL query that does the following:

        Column A     Column B

Row1    2861682      sum(Row1 to Row5)
Row2    2522226      sum(Row2 to Row5)  
Row3    2285983      sum(Row3 to Row5)
Row4    2096046      sum(Row4 to Row5)  
Row5    1935355      sum(Row5)  

This is the data I have in a table column.

Now I need to calculate

sum(Row1 to Row5) 
sum(Row2 to Row5) 
sum(Row3 to Row5) 
sum(Row4 to Row5)
sum(Row5)

Thanks

Это было полезно?

Решение

The standard SQL form for this uses a correlated subquery:

select t.*,
       (select sum(B)
        from t t2
        where t2.A >= t.A
       ) as TheSum
from t;

Some databases also support window/analytic functions that allow cumulative sums.

EDIT:

Netezza is one of the databases that support cumulative sums using window functions (thanks to its Postgres heritage, I imagine). You can also express this as:

select t.*,
       sum(B) over (order by A desc) as TheSum
from t

EDIT II:

I don't have a Netezza database to test on, but it does have the RowId column. You might be able to use this, although I cannot find any documentation that guarantees its being monotonically increasing. In fact, I'm pretty sure that for a parallel load, the rowid would not be monotically assigned.

The query would look like:

select t.*,
       sum(B) over (order by rowid desc) as TheSum
from t
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top