SUM基于标准

时间:2017-10-05 19:43:23

标签: sql postgresql

我如何SUM"订单"当有一个值为"花费"以及它从最旧到最新之后出现的NULL行?

当前输出:

    Date   |   Product  |   Spend   |  Orders
------------------------------------------------
2017-09-18    Product A     NULL         7
2017-09-11    Product A     NULL         7
2017-09-04    Product A    1000.00      16
2017-08-28    Product A     NULL         7
2017-08-21    Product A    2000.00      35
2017-08-14    Product A    1000.00      20
2017-08-07    Product A     NULL         3
2017-07-31    Product A     NULL         3
2017-07-24    Product A    1000.00      14

期望的输出:

    Date   |   Product  |   Spend   |  Orders  | SUMMED Orders
---------------------------------------------------------------
2017-09-18    Product A     NULL         7          NULL
2017-09-11    Product A     NULL         7          NULL
2017-09-04    Product A    1000.00      16          30 (16 + 7 + 7)
2017-08-28    Product A     NULL         7          NULL
2017-08-21    Product A    2000.00      35          42 (35 + 7)
2017-08-14    Product A    1000.00      20          20 (20)
2017-08-07    Product A     NULL         3          NULL
2017-07-31    Product A     NULL         3          NULL
2017-07-24    Product A    1000.00      14          20 (14 + 3 + 3)

我在SUMMED Orders列中写了数学表达式,以显示我是如何想出新总数的。

谢谢。

2 个答案:

答案 0 :(得分:1)

您可以通过计算较旧的非空行数来为行分配组。然后,您可以使用此组来计算总和:

select t.*,
       sum(orders) over (partition by product, grp) as summed_orders
from (select t.*,
             sum( (spend is not null)::int ) over (partition by product order by date asc) as grp
      from t
     ) t;

这不会删除第一行。我不确定删除它的逻辑是什么。

答案 1 :(得分:0)

select "date", product, spend, orders, sum(orders) over (order by "date") rt
  from t1
 order by "date" desc , spend nulls first;