想要为多个客户数据做累积总和

时间:2018-03-20 14:22:40

标签: sql postgresql cumulative-sum

我在postgresql中的链接中也是如此,我可以生成累积和的系列。但它适用于单一记录。我有多个客户数据存储在一个表中,我想为所有客户做总结。以下是代码:

WITH cte AS (
SELECT date_trunc('month', pe.pdate) mon, sum(pei.pamt) as mon_sum 
FROM pur_entry_item pei, pur_entry pe, customer cus WHERE cus.id =  pei.cust_id 
AND pe.id = pei.pid AND cus.id=101 GROUP BY date_trunc('month', pe.pdate)
order by date_trunc('month', pe.pdate)
) 

SELECT to_char(mon, 'Mon YYYY') AS mon_text, 
COALESCE(sum(c.mon_sum) OVER (PARTITION BY id ORDER BY mon),0) AS running_sum 
FROM generate_series('2017-01-01'::date, now(),interval '1 month') mon 
LEFT JOIN cte c USING (mon);

通过使用上述查询,如果在月份数据存在与否之间,则1个客户可以从01-01-2017到当前日期进行累积求和。现在我必须为多个客户这样做。知道我该怎么处理这个查询。

TABLE 1 := pur_entry    TABLE 3 := customer
  id     pdate           id cus_name
  1    01-04-2017         1  nikita
  2    04-06-2017         2  disha
  3    10-06-2017         3  sonal
  4    10-09-2017
  5    01-06-2017         
  6    04-08-2017         
  7    10-10-2017        
  8    10-02-2017

TABLE 2 := pur_entry_item
 id cust_id pamt  pid
 1     1    1000   1
 2     1    200    2 
 3     1    500    2
 4     1    500    3
 5     1    100    4
 2     2    600    5 
 3     2    300    6
 4     2    200    7
 5     2    800    8

I want below result:
cut_id   date     amt
 1      04,2017  1200
 1      05,2017  1000
 1      06,2017  2200
 1      07,2017  2200
 1      08,2017  2200
 1      09,2017  2300
 1      10,2017  2300
 1      11,2017  2300
 1      12,2017  2300
 1      01,2018  2300
 1      02,2018  2300
 1      03,2018  2300
 2      04,2017  0
 2      05,2017  0
 2      06,2017  600
 2      07,2017  600
 2      08,2017  900
 2      09,2017  900
 2      10,2017  1200
 2      11,2017  1200
 2      12,2017  1200
 2      01,2018  1200
 2      02,2018  2000
 2      03,2018  2000

客户明智的累积每月购买金额的总和。如果只有一个客户为多个客户生成系列只生成一次系列,则上述代码将起作用。

提前致谢。

1 个答案:

答案 0 :(得分:0)

我希望累积的总和代码看起来像这样:

SELECT cus.id, date_trunc('month', pe.pdate) as mon, SUM(pei.pamt) as mon_sum,
       SUM(SUM(pei.pamt)) OVER (PARTITION BY cus.id ORDER BY MIN(pe.pdate)) as cumulative_mon_sum
FROM customer cus JOIN
     pur_entry_item pei
     ON cus.id =  pei.cust_id  JOIN
     pur_entry pe 
     ON pe.id = pei.pid 
WHERE cus.id = 101
GROUP BY cus.id, date_trunc('month', pe.pdate)
ORDER BY cus.id, date_trunc('month', pe.pdate);

您可以删除WHERE子句并为所有客户执行此操作。