tags:

views:

206

answers:

2

I've got a table that looks like this:

Code    Mark Date Notional
Beta    5/1/2008 $1,102,451.00
Beta    5/2/2008 $1,102,451.00
Beta    5/5/2008 $1,102,451.00
Beta    5/6/2008 $1,102,451.00

I need to create a table that has all of the Mark Dates in one column and the difference between each adjacent Mark Date when sorted in another column. This is the SQL I've written:

SELECT 
    Current.[Mark Date],
    Prev.[Mark Date],
    (DATEDIFF("d", Prev.[Mark Date], Current.[Mark Date])/365)

FROM Notional as Prev, Notional as Current
WHERE (Prev.[Mark Date] = (Current.[Mark Date]-1));

However, this SQL will not join over the weekend 5/5/2008 -> 5/2/2008 for example or on long weekends. How would I go about getting the table to self join over non contiguous dates? Thanks for all the help!

+1  A: 

You can try to use ROW_NUMBER when selecting and join on that order by the date.

EDIT. Done with joins.

What you can do is to join the table to itself, on dates bigger than that row, and then group by and select the min.

Something like this

DECLARE @Table TABLE(
     DateVal DATETIME
)

INSERT INTO @Table SELECT '01 May 2009'
INSERT INTO @Table SELECT '02 May 2009'
INSERT INTO @Table SELECT '05 May 2009'
INSERT INTO @Table SELECT '06 May 2009'

SELECT  t.DateVal,
     MIN(tNext.DateVal) NextDate
FROM    @Table t LEFT JOIN
     @Table tNext ON t.DateVal < tNext.DateVal
GROUP BY t.DateVal

I know this is Sql Server code, but can easily be changed to MS Access.

This should return the folowing:

StartDate                  EndDate
2009-05-01 00:00:00.000 2009-05-02 00:00:00.000
2009-05-02 00:00:00.000 2009-05-05 00:00:00.000
2009-05-05 00:00:00.000 2009-05-06 00:00:00.000
2009-05-06 00:00:00.000 NULL
astander
Is that considered good form?
Tyler Brock
+1  A: 

The only way to do this is to use ROW_NUMBER (and ROW_NUMBER+1) on a select ordered by date for an SQL that supports row numbers OR to create a temporary table with an auto increment key which you populate in date order.

There is no other way without resorting to a non-join solution (that is a loop.)

Hogan
Ok yeah, I have to create a temporary table with the auto increment key because I'm using ACCESS 2007... any idea on how to do that?
Tyler Brock
not off the top of my head -- I believe in access you use the auto keyword when you declare the table.make sure if you are creating a temporary table you don't put all the fields in the temp table -- best is just have a temp table with two fields -- autoinckey and external key (the external key points to Notional table's key). This will be faster.
Hogan
This is not true. It can be done without using loops. Please see my answer for a brief description
astander