如何从SQL中的当前行数据中减去前一行数据的总和

时间:2016-11-19 09:34:48

标签: sql group-by firebird

我有一个表火鸟,它用3列(星期,日期,金额)调用t1。 我需要根据周列和

对数据进行分组
  1. 总和正数(库存)
  2. 总和负数(已售出)
  3. 从已售出(当前记录)中减去库存(上一记录)
  4. 我附上了t1和t2的图片

    T1:

    week    date    amount
    18/06/2016  14/06/2016  94
    18/06/2016  15/06/2016  0
    18/06/2016  16/06/2016  0
    18/06/2016  17/06/2016  0
    18/06/2016  18/06/2016  -1
    25/06/2016  19/06/2016  -2
    25/06/2016  20/06/2016  -1
    25/06/2016  21/06/2016  0
    25/06/2016  22/06/2016  -1
    25/06/2016  23/06/2016  -1
    25/06/2016  24/06/2016  -3
    25/06/2016  25/06/2016  -1
    02/07/2016  26/06/2016  -1
    02/07/2016  27/06/2016  -2
    02/07/2016  28/06/2016  0
    02/07/2016  29/06/2016  1
    02/07/2016  30/06/2016  0
    02/07/2016  01/07/2016  -1
    09/07/2016  03/07/2016  -1
    09/07/2016  04/07/2016  -1
    09/07/2016  05/07/2016  -2
    09/07/2016  06/07/2016  0
    09/07/2016  07/07/2016  -2
    09/07/2016  08/07/2016  -1
    09/07/2016  09/07/2016  -3
    

    T2:

    week      sold     stock
              null      94
    18/06/2016  1       93
    25/06/2016  9       84
    02/07/2016  3       81
    09/07/2016  9       72
    

    我正在使用Firebird,我的最终脚本应该在firebird或标准sql中运行 感谢

    enter image description here

1 个答案:

答案 0 :(得分:1)

基本查询似乎是:

select week, sum(case when amount > 0 then amount else 0 end) as stock,
       sum(case when amount < 0 then amount else 0 end) as sold
from t1
group by week;

Firebird不支持窗口函数,但您也可以使用相关子查询。 CTE有帮助。我认为是:

with t as (
      select week, sum(case when amount > 0 then amount else 0 end) as stock,
             sum(case when amount < 0 then amount else 0 end) as sold
      from t1
      group by week
     )
select t.*,
       (select sum(t2.stock) + sum(t2.sold)
        from t t2
        where t2.week <= t.week
       ) as stock
from t;

编辑:

使用窗口功能(在Firebird 3中),这更容易:

select week, sum(case when amount > 0 then amount else 0 end) as stock,
       sum(case when amount < 0 then amount else 0 end) as sold,
       sum(amount) over (order by week) as 
from t1
group by week;