Search code examples
sqlvbams-access

MS Access / VBA - How can I split rows in a Date Range


I have the following table and i want to split the date range into multiple rows if the start date and the end date have a difference greater than 1 month and depending on how many months were in that period split the "net price" in that many pieces.

The Existing table looks like this:

MesspNr RechnNr AbDat BisDat NettBetr
ALT_102420 1 01.04.2016 30.06.2016 1702.98
ALT_102420 2 01.07.2016 30.09.2016 1779.63
ALT_102420 3 01.11.2016 30.11.2016 1020.60

And the outcome table should look like this:

MesspNr RechnNr AbDat BisDat NettBetr
ALT_102420 1 01.04.2016 30.04.2016 567.66
ALT_102420 1 01.05.2016 31.05.2016 567.66
ALT_102420 1 01.06.2016 30.06.2016 567.66
ALT_102420 2 01.07.2016 30.07.2016 593.21
ALT_102420 2 01.08.2016 31.08.2016 593.21
ALT_102420 2 01.09.2016 30.09.2016 593.21
ALT_102420 3 01.11.2016 30.11.2016 1020.60

I have tried it using the solution on this link but I can't get it to work. Even in it's "purest" copy pasted form it just sets AbDat and BisDat to the same Date and doesn't create new rows. I would greatly appriciate any form of help on splitting the price and creating new rows.


Solution

  • First, create a small query and save it as Ten:

    SELECT DISTINCT Abs([id] Mod 10) AS N FROM MSysObjects;
    

    Then use this in a Cartesian (multiplying) query to generate the months:

    SELECT 
        Betrag.MessNr, 
        Betrag.RechnNr, 
        DateAdd("m", [N], [AbDat]) AS AbDatum, 
        DateAdd("d", -1, DateAdd("m", [N] + 1, [AbDat])) AS BisDatum, 
        [NettBetr] / (1 + DateDiff("m", [AbDat], [BisDat])) AS NettBetrag
    FROM 
        Betrag, 
        Ten
    WHERE
        Ten.N <= DateDiff("m", [AbDat], [BisDat])
    ORDER BY 
        Betrag.MessNr, 
        Betrag.RechnNr, 
        DateAdd("m", [N], [AbDat]);
    

    Output:

    MessNr RechnNr AbDatum BisDatum NettBetrag
    ALT_102420 1 01-04-2016 30-04-2016 567,66
    ALT_102420 1 01-05-2016 31-05-2016 567,66
    ALT_102420 1 01-06-2016 30-06-2016 567,66
    ALT_102420 2 01-07-2016 31-07-2016 593,21
    ALT_102420 2 01-08-2016 31-08-2016 593,21
    ALT_102420 2 01-09-2016 30-09-2016 593,21
    ALT_102420 3 01-11-2016 30-11-2016 1020,60