Postgresql运行以前组的总和?

时间:2013-09-14 22:48:11

标签: postgresql grouping window-functions

鉴于以下数据:

sequence | amount
1          100000
1          20000
2          10000
2          10000

我想编写一个sql查询,它给出了当前序列的总和,加上前一个序列的总和。像这样:

sequence | current | previous
1 120000 0
2 20000 120000

我知道解决方案可能涉及窗口函数,但我不太清楚如何在没有子查询的情况下实现它。

2 个答案:

答案 0 :(得分:3)

SQL Fiddle

select
    seq,
    amount,
    lag(amount::int, 1, 0) over(order by seq) as previous
from (
    select seq, sum(amount) as amount
    from sa
    group by seq
) s
order by seq

答案 1 :(得分:0)

如果您的序列是“顺序的”没有漏洞,您只需执行以下操作:

SELECT t1.sequence,
  SUM(t1.amount),
  (SELECT SUM(t2.amount) from mytable t2 WHERE t2.sequence = t1.sequence - 1)
FROM mytable t1
GROUP BY t1.sequence
ORDER BY t1.sequence

否则,您可以执行以下操作而不是t2.sequence = t1.sequence - 1

SELECT t1.sequence,
  SUM(t1.amount),
  (SELECT SUM(t2.amount) 
   from mytable t2 
   WHERE t2.sequence = (SELECT MAX(t3.sequence) 
                        FROM mytable t3 
                        WHERE t3.sequence < t1.sequence))
FROM mytable t1
GROUP BY t1.sequence
ORDER BY t1.sequence;

您可以在this fiddle

中看到这两种方法