4

i'm aggregating facebook "like" counts for urls over time. each hour, i check the "like" count and insert it into a timestamped row. how can i get the difference in total between the new row and the previous hour's row?

eg,

  1. insert total=5 for id=1 at 2pm
  2. insert total=12, diff_since_last=7 for id=1 at 3pm

thanks!

2 Answers 2

6

This should do it.

SELECT id, 
       total, 
       total - lag(total) over (partition by id order by timestamp_column) as diff_since_last
FROM the_table_with_no_name
Sign up to request clarification or add additional context in comments.

Comments

0

When I tried a_horse_with_no_name's solution I had to remove the 'partition by id' portion to get a result (I'm using PG 9.2)

SELECT id, total, total - lag(total) over (order by timestamp_column) as diff_since_last FROM the_table_with_no_name

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.