1

Given the following data:

sequence | amount
1          100000
1          20000
2          10000
2          10000

I'd like to write a sql query that gives me the sum of the current sequence, plus the sum of the previous sequence. Like so:

sequence | current | previous
1 120000 0
2 20000 120000

I know the solution likely involves windowing functions but I'm not too sure how to implement it without subqueries.

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

4 Comments

It's that lag feature that I could find properly documented here postgresql.org/docs/9.2/static/functions-window.html. Thanks a lot.
what are the other options to lag, and what specifically is lag doing there? Thanks.
Actually, re-reading the docs for lag makes it clear now. Thanks again!
+1 for nice formaitting and lowercase keywords, I really hate UPPERCASE SQL statements, it's like we're still in 1980..
0

If your sequence is "sequencial" without holes you can simply do:

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

Otherwise, instead of t2.sequence = t1.sequence - 1 you could do:

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;

You can see both approaches in this fiddle

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.