2010-08-21 91 views
4

我聚合Facebook「喜歡」隨着時間的推移計數的網址。每小時,我檢查「喜歡」數量並將其插入時間戳行。我怎樣才能得到新的行和前一小時的行之間的總差異?選擇行之間的差異(Postgres)

例如,

  1. 插入件爲ID = 1的總含量= 5在下午2點
  2. 插入總= 12,對於diff_since_last ID = 7 = 1在下午3個

謝謝!

回答

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 
0

當我試圖a_horse_with_no_name的解決方案,我有 '按id分區' 刪除部分得到的結果(我使用的是PG 9.2)

SELECT ID, 總, 總 - 滯後( total)over(order by timestamp_column)as diff_since_last FROM the_table_with_no_name