I have a table with two fields timestamp and value. new values are added to the table every 15min. i want to find the change in value from one record to the next. how do i do this using sql.
It always helps if you could specify what database you use. Anyway, I’ll assume you use Oracle. You can use the power of analytic functions in Oracle to accomplish your goal.
Study the following example carefully. It shows how the "lag" analytic function can be used effectively to find out sliding-window differences in a single-pass through the table.
===================================================
test@ORA10G>
test@ORA10G> –
test@ORA10G> alter session set
2 nls_date_format = ‘dd-Mon-yyyy hh:mi:ss AM’;
Session altered.
test@ORA10G> select * from t;
TSTAMP VALUE
———————– ———-
01-Jan-2009 08:00:00 AM 23.5
01-Jan-2009 08:15:00 AM 28.8
01-Jan-2009 08:30:00 AM 33.1
01-Jan-2009 08:45:00 AM 49.9
01-Jan-2009 09:00:00 AM 55.8
01-Jan-2009 09:15:00 AM 19.6
01-Jan-2009 09:30:00 AM 20.3
01-Jan-2009 09:45:00 AM 66.2
01-Jan-2009 10:00:00 AM 64.7
9 rows selected.
test@ORA10G> –
test@ORA10G> select tstamp,
2 value,
3 lag (value) over (order by tstamp) lag,
4 value - lag (value) over (order by tstamp) diff
5 from t;
TSTAMP VALUE LAG DIFF
———————– ———- ———- ———-
01-Jan-2009 08:00:00 AM 23.5
01-Jan-2009 08:15:00 AM 28.8 23.5 5.3
01-Jan-2009 08:30:00 AM 33.1 28.8 4.3
01-Jan-2009 08:45:00 AM 49.9 33.1 16.8
01-Jan-2009 09:00:00 AM 55.8 49.9 5.9
01-Jan-2009 09:15:00 AM 19.6 55.8 -36.2
01-Jan-2009 09:30:00 AM 20.3 19.6 .7
01-Jan-2009 09:45:00 AM 66.2 20.3 45.9
01-Jan-2009 10:00:00 AM 64.7 66.2 -1.5
9 rows selected.
test@ORA10G>
test@ORA10G>
===================================================
I used Oracle 10g. Analytic functions were introduced in Oracle 8i. For versions older than that, you’d have to join the table with itself, which would result in multiple passes through the same table. Use of analytic functions result in much more efficient queries.
HTH,
techieguy