简体   繁体   中英

MS Access: Group by months for each month between Start Date and End Date

I have these four data fields - ID, SubscriptionStartDate, SubscriptionEndDate and MonthlyCost in MS Access. Subscription Start and End Date will cover multiple months or even years, I want to sum MonthlyCost for each individual month between Start and End Date for all the IDs.

Using SQL in Access, I am looking for an output like:

Month TotalMonthlyCost

Jan-13 100000 -> total monthly cost for Jan-13, summed across all the IDs.

Feb-13 150000 -> total monthly cost for Feb-13, summed across all the IDs. ...

I think that you could do something like this:

select
    m.month
    ,sum(d.MonthlyCost)
from
    months as m
    inner join data as d
        on d.SubscriptionStartDate < m.endDate
        and d.SubscriptionEndDate > m.start
group by
    m.month

You would need to create the table "months" that would look like this:

   month   |    start   |   end
 'jan-13'  | 01/01/2013 | 31/01/2013
 'feb-13'  | 01/02/2013 | 28/02/2013
 'mar-13'  | 01/03/2013 | 31/03/2013

but this is saying if you are in that month at all (even for one day) then you rmonthly subscription should be added. Is that correct?

Note: i don't have access here and i cant remember if my syntax is perfect for access. (i think you need brackets in the join clauses or something)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM