4

我有一个包含以下字段的表:

season, collection, product_key, units_sold

我想添加额外的

cumulative_sold column(aggreate of previous rows values)

应该满足order by season, collection,units_sold

sample input
---------- 
ss,f1,1,3
ss,f1,2,4
ss,f1,3,4
ss,f2,1,1
ss,f2,5,1

expected output 
--------------
ss,f1,1,3,3 
ss,f1,2,4,7(3+4)
ss,f1,3,4,11(3+4+4)
ss,f2,1,1,1
ss,f2,5,1,2(1+1)
4

1 回答 1

1

您可以使用相关子查询进行累积和:

select season, collection, product_key, units_sold,
       (select sum(units_sold)
        from t t2
        where t2.season < t.season or
              t2.season = t.season and t2.collection < t.collection or
              t2.season = t.season and t2.collection = t.collection and t2.units_sold <= t.units_sold
       ) as cumsum            
from t;

这是标准 SQL。如果您有大量数据,则需要在t(season, collection, units_sold).

编辑:

如果您只想为特定季节中的特定集合而不是总体累积总和:

select season, collection, product_key, units_sold,
       (select sum(units_sold)
        from t t2
        where t2.season = t.season and t2.collection = t.collection and
              t2.units_sold <= t.units_sold
       ) as cumsum            
from t;

编辑二:

这是一种非常标准的 SQL 类型。如果您能正确回答问题,将会有所帮助。要处理重复项units_sold

select season, collection, product_key, units_sold,
       (select sum(units_sold)
        from t t2
        where t2.season = t.season and t2.collection = t.collection and
              (t2.units_sold < t.units_sold or
               t2.units_sold = t.units_sold and t2.product_key <= t.product_key
              )
       ) as cumsum            
from t;
于 2013-09-19T10:52:15.823 回答