SQL: Count the entities travelling with the between dates

Viewed 29

This is what my table looks like:

carid date of departure date of arrival
1 12-03-2022 16-03-2022
2 15-03-2022 18-03-2022
3 16-03-2022 19-03-2022
4 20-03-2022 23-03-2022

And I need the output to be like:

Date amount
12-03-2022 1
13-03-2022 1
14-03-2022 1
15-03-2022 2
16-03-2022 3
17-03-2022 2

How can I achieve it?

1 Answers

Suppose your data table name is TRAVELS, create a new table RESULTS with these fields:

xdate as date, primary key
n as integer

Now, try something like this code:

docmd.runsql "delete from RESULTS"
dim TRAVELS as recordset
dim RESULTS as recordset
set TRAVELS= currentdb.openrecordset("TRAVELS" , dbopenforwardonly , dbreadonly)
set RESULTS= currentdb.openrecordset("RESULTS")
RESULTS.index= "primarykey"
dim xdate as date
do while not TRAVELS.eof
    xdate= TRAVELS!date_of_departure
    do while xdate <= TRAVELS!date_of_arrival
        RESULTS.seek "=" , xdate
        if RESULTS.nomatch then
            RESULTS.addnew
            RESULTS!xdate= xdate
            RESULTS!n= 1
            RESULTS.update
        else
            RESULTS.edit
            RESULTS!n= RESULTS!n + 1
            RESULTS.update
        end if
        xdate= dateadd("d" , 1 , xdate)
    loop
    TRAVELS.movenext
loop
TRAVELS.close
set TRAVELS= nothing
RESULTS.close
set RESULTS= nothing
Related