OracleBrains.Com header image 2

Time-series related query at Oracle Forum

December 13th, 2006 by Rajender Singh · 3 Comments

Today I came across one interesting question at Oracle Forum

Dear experts!
Please help me with this kind of query!
Suppose that I have a table like the following to keep track of moving path of an item

location datetime

l1 2006/10/01
l1 2006/10/20
l1 2006/11/01
l2 2006/11/03
l2 2006/11/19
l1 2006/11/28
l1 2006/12/10

How can I figure which location the object used to be at and the duration it stayed there over time, so that the result of the query look like this:
location date_start date_end
l1 2006/10/01 2006/10/20
l2 2006/11/03 2006/11/19
l1 2006/11/28 2006/12/10

Thank you very much!

——————————————————————–

I though lot about it, and gave him following answer:

Ok first I created one table:

CREATE TABLE TEMP1234(
location VARCHAR2(6),
date_start DATE
);
ALTER SESSION SET NLS_DATE_FORMAT=’YYYY/MM/DD’;

INSERT into TEMP1234 values (’l1′, ‘2006/10/01′);
INSERT into TEMP1234 values (’l1′, ‘2006/10/20′);
INSERT into TEMP1234 values (’l1′, ‘2006/11/01′);
INSERT into TEMP1234 values (’l2′, ‘2006/11/03′);
INSERT into TEMP1234 values (’l2′, ‘2006/11/19′);
INSERT into TEMP1234 values (’l1′, ‘2006/11/28′);
INSERT into TEMP1234 values (’l1′, ‘2006/12/10′);

COMMIT;

Now once it is done, now issue following SQL.

SELECT location, date_start, (MAX(date_start) OVER ( order by date_start rows
between current row and 1 following)) as date_end
FROM TEMP1234
ORDER BY date_start
/

Result will be as follows:
LOCATI DATE_START DATE_END
—— ———- ———-
l1 2006/10/01 2006/10/20
l1 2006/10/20 2006/11/01
l1 2006/11/01 2006/11/03
l2 2006/11/03 2006/11/19
l2 2006/11/19 2006/11/28
l1 2006/11/28 2006/12/10
l1 2006/12/10 2006/12/10

7 rows selected.
I hope this will solve your problem.


Tags: Interesting Coding Showcase · SQL and PL/SQL

3 responses so far ↓

  • 1 APC // Dec 13, 2006 at 9:38 pm

    It is an interesting problem.

    You must admit that Rob van Wijk’s solution more closely matched the questioner’s requirements: http://forums.oracle.com/forums/message.jspa?messageID=1596546#1596546

    Cheers, APC

  • 2 Rajender Singh // Dec 13, 2006 at 10:44 pm

    Yes Andrew, I agree with you.

    I didn’t completly understood the question. Actully I connected this problem to my own problem.

    For exmaple
    In our Fixed Asset Module I design the Fixed Asset Location table like Fixed Asset Code, Location Code, From Date, To Date to track the history and current location of the Fixed Asset. When ever an Asset move to new location, a record is added to this table with From Date as current date and record previous to it is updated with To Date as current date.

    Now with this query (offcourse with little improvement for last record) I don’t need to store “To Date” in my table.

  • 3 Ray DeBruyn // Dec 7, 2007 at 2:39 am

    You’re still better off storing the date for better performance.

Leave a Comment