1

I have a table with data that is updated every 5 minutes.

| TimeStamp | Data |
|   1       |    2 |
|   2       |    8 |
|   3       |   16 |

How can I select this data in such a way that it does not show the data, but the difference between the last timestamp, like this:

| TimeStamp | Data |
|   1       |    2 |
|   2       |    6 |
|   3       |    8 |
zlack
  • 13
  • 3

2 Answers2

0

If your timestamps have no gaps (as in the example in the question):

select t.timestampe,
       t.data - coalesce(tprev.data, 0) as data
from table t left outer join
     table tprev
     on t.timestamp = tprev.timestemp + 1;

If you have gaps, this may not work the way you want.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

If the scenario envisaged by Gordon materializes, then you can do something like this...

SELECT x.timestamp
     , x.data-COALESCE(MAX(y.data),0) data 
  FROM my_table x 
  LEFT 
  JOIN my_table y 
    ON y.timestamp < x.timestamp 
 GROUP 
    BY x.timestamp;
Strawberry
  • 33,750
  • 13
  • 40
  • 57
  • There is seems to be a problem when there are gaps. If I'm getting 0 data for a while, I end up with negative data and off numbers. Any suggestion about how to fix that? – zlack Feb 10 '14 at 09:22
  • I suggest you post up an sqlfiddle demonstrating the problem. – Strawberry Feb 10 '14 at 09:43