简体   繁体   中英

How to Get Aggregated Sums At Specified Dates Using SQL Statement

I am trying to generate sums of transactions which is contained in a SQL Server table using this script:

Select Category,Sum(Items) as CategoryTotals 
from TransactionsTable  
where TransDate <=ReportingDate
Group By Category

I also have a list of dates for which this information is required as:

Select ReportingDates From AllMyDatesTable

Can anyone assist me with how I can structure a query to join the two queries to get a list of CategoryTotals at Specified dates similar to

Select ReportingDates,CategoryTotals from (My Two Tables)?

Any help appreciated

Something like this? If you want to show dates even if no transaction is found go for left join instead of inner join

Select d.ReportingDates,t.Category,Sum(d.Items)
  from AllMyDatesTable d inner join TransactionsTable t 
    on d.ReportingDates = t.TransDate 
   and d.TransDate <= ReportingDate
 group by d.ReportingDates,t.Category

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