Question

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!

Was it helpful?

Solution

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.)

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top