选择行间差异(Postgres)

时间:2010-08-21 18:50:37

标签: database postgresql

随着时间的推移,我正在整合网址“喜欢”的网址。每小时,我检查“喜欢”计数并将其插入带时间戳的行。如何获得新行与前一小时行之间的总差异?

例如

  1. 在下午2点为id = 1插入total = 5
  2. insert total = 12,diff_since_last = 7 for id = 1 at 3pm
  3. 谢谢!

2 个答案:

答案 0 :(得分:6)

这应该这样做。

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

答案 1 :(得分:0)

当我尝试a_horse_with_no_name的解决方案时,我不得不删除'id by id'部分以获得结果(我正在使用PG 9.2)

SELECT id,        总,        total - lag(total)over(timestamp_column的顺序)为diff_since_last FROM the_table_with_no_name