2017-10-05 66 views
0

如何在「支出」值和「從最老到最新」之後出現空行時彙總「訂單」?SUM基於關鍵標準

電流輸出:

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) 

我寫的數學表達式中具有總訂單欄,顯示我怎麼想出了新的總。

謝謝。

+0

看來你按正確的順序排序? –

+0

@ TedatORCL.Pro我更正了日期以匹配。謝謝 –

回答

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; 

這不會刪除第一行。我不確定刪除它的邏輯是什麼。

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

幾乎在那裏,但每次有「花費」值時,我都需要重置「rt」。這個「rt」列不斷總結每種產品。 –

+0

好吧,我只是一個假設,讓我編輯和修復你 –

+0

現在應該運行良好,試試看,讓我們知道。 –