Quantcast
Viewing latest article 2
Browse Latest Browse All 3

select time intervals in sql

consider the following example :

CREATETABLE elem (
    id INTEGER,
    name VARCHAR,
    num INTEGER
);
CREATETABLE proxy (
    elem_id INTEGER,
    time_id INTEGER
);
CREATETABLETIME(
    id INTEGER,
    TIMESTAMP DATESTAMP
);

INSERTINTO elem VALUES(0,"one",1);
INSERTINTO elem VALUES(1,"one",2);
INSERTINTO elem VALUES(2,"one",3);
INSERTINTO elem VALUES(3,"two",1);

INSERTINTO proxy VALUES(0,0);
INSERTINTO proxy VALUES(0,1);
INSERTINTO proxy VALUES(1,2);
INSERTINTO proxy VALUES(1,3);
INSERTINTO proxy VALUES(2,4);
INSERTINTO proxy VALUES(3,4);

INSERTINTOTIMEVALUES(0,"12/12/2008");
INSERTINTOTIMEVALUES(1,"13/12/2008");
INSERTINTOTIMEVALUES(2,"14/12/2008");
INSERTINTOTIMEVALUES(3,"15/12/2008");
INSERTINTOTIMEVALUES(4,"16/12/2008");

What I want is to write a query that will group for each (name,num) the start and end edges of the interval given by the table time:

For example:

one | 1 | 12/12/2008 | 13/12/2008
one | 2 | 14/12/2008 | 15/12/2008
one | 3 | 16/12/2008 | 16/12/2008
two | 1 | 16/12/2008 | 16/12/2008

First we create a simple view to unclutter the query statement.

 CREATE temp VIEW all_t ASSELECT elem.name,elem.num,TIME.TIMESTAMPFROM elem,TIME,proxy WHERE proxy.elem_id = elem.id ANDTIME.id = proxy.time_id ;

Then the sql query is pretty straightforward ...

SELECT name,num,MIN(TIMESTAMP),MAX(TIMESTAMP)FROM all_t GROUPBY name, num;
one|1|12/12/2008|13/12/2008
one|2|14/12/2008|15/12/2008
one|3|16/12/2008|16/12/2008
two|1|16/12/2008|16/12/2008

Viewing latest article 2
Browse Latest Browse All 3

Trending Articles