Inserting Weekends into Table with only Weekdays MS Access

后端 未结 2 468
遥遥无期
遥遥无期 2021-01-25 08:10

I\'m needing to insert the weekends into a table that only has weekdays and then assign the last known value to the weekend values. I know I\'m going to need an Insert Query, al

相关标签:
2条回答
  • 2021-01-25 08:31

    This is a SQL based solution.

    This gets all records where for customer x exists records for Friday + the following Monday but not for Saturday.

    SELECT a1.*
    FROM Archive a1
    INNER JOIN Archive a2 ON (
           (a1.Nbr = a2.Nbr) 
       AND (a1.ExtendedNbr = a2.ExtendedNbr) 
       AND (a1.ValDate + 3 = a2.ValDate) 
       AND (DatePart("w", a1.ValDate) = 6)
      )
    WHERE NOT EXISTS
    (SELECT * FROM Archive a3 
     WHERE a3.Nbr = a1.Nbr
     AND a3.ValDate = a1.ValDate + 1)
    

    and you can use that to insert the Saturdays:

    INSERT INTO Archive ([Customer Name], Nbr, City, [Value of Day], ExtendedNbr, ValDate)
    SELECT a1.[Customer Name], a1.Nbr, a1.City, a1.[Value of Day], a1.ExtendedNbr, a1.ValDate + 1
    FROM Archive a1
    INNER JOIN Archive a2 ON (
           (a1.Nbr = a2.Nbr) 
       AND (a1.ExtendedNbr = a2.ExtendedNbr) 
       AND (a1.ValDate + 3 = a2.ValDate) 
       AND (DatePart("w", a1.ValDate) = 6)
      )
    WHERE NOT EXISTS
    (SELECT * FROM Archive a3 
     WHERE a3.Nbr = a1.Nbr
     AND a3.ValDate = a1.ValDate + 1)
    

    To insert the Sundays, use the same, but replace + 1 by + 2 in both places.

    To insert random single missing days (bank holidays), change a1.ValDate + 3 to a1.ValDate + 2, and remove AND (DatePart("w", a1.ValDate) = 6)

    Edit

    An alternate version if DatePart() inside JOIN gives trouble:

    INSERT INTO Archive ([Customer Name], Nbr, City, [Value of Day], ExtendedNbr, ValDate)
    SELECT a1.[Customer Name], a1.Nbr, a1.City, a1.[Value of Day], a1.ExtendedNbr, a1.ValDate + 1
    FROM Archive a1
    INNER JOIN Archive a2 ON (
           (a1.Nbr = a2.Nbr) 
       AND (a1.ExtendedNbr = a2.ExtendedNbr) 
       AND (a1.ValDate + 3 = a2.ValDate) 
      )
    WHERE NOT EXISTS
    (SELECT * FROM Archive a3 
     WHERE a3.Nbr = a1.Nbr
     AND a3.ValDate = a1.ValDate + 1)
    AND (DatePart("w", a1.ValDate) = 6)
    
    0 讨论(0)
  • 2021-01-25 08:43

    When entering dates as query criteria, enclose them in pound signs (#)

    DoCmd.RunSQL "INSERT INTO Archive SELECT * FROM Archive WHERE ValDate = #" & DateVal & "#"
    

    Edited 1

    Do While Not rs.EOF
             If IsNull(DLookup("ValDate", "Archive", "ValDate=#" & DateAdd("d", 1, ValDate) & "#")) = True Then
            rs.AddNew
            rs![ValDate] = DateVal
            rs.Update
        End If
        rs.MoveNext
    Loop
    
    0 讨论(0)
提交回复
热议问题