如何根据日期范围对值进行求和并按最大日期分组?

时间:2019-09-14 02:31:03

标签: sql date sum

我有一个类似以下的数据集-按周和产品汇总的数量和销售额$

navigationController.tabBarController.tabBar.compactMap{$0 as? UIImageView}.first.alpha = 1

对于每周,我需要对该周加上前3周的数量和销售额进行汇总

期望的结果将是:

Week    Product     Quantity    Sales
----    -------     --------    -----
1       12a         6           600
2       12a         4           400
3       12a         3           300
4       12a         1           100
5       12a         3           300 
6       12a         1           100
7       12a         4           400 
8       12a         6           600
9       12a         2           200

我觉得我需要一个循环来每周评估一次

1 个答案:

答案 0 :(得分:1)

使用窗口功能:

select t.*,
       sum(quantity) over (partition by product
                        order by week
                        rows between current row and 3 following
                       ) as quantity,
       sum(sales) over (partition by product
                        order by week
                        rows between current row and 3 following
                       ) as sales
from t;