简体   繁体   中英

T-SQL query that can sum up expenses for the current month, what that sumed average is for all months

I have a table with Month_Id(int), Year(nvarchar), Expenses(money) .

I need a report that shows the sum of a current month, and what the average of that month would be.

This is what I got so far.

SELECT     dt.Date, dt.Other_Revenue, dt.Month_Id, dt.Date_Year
FROM         S1_Rpt_Daily_Totals 
WHERE     (dt.Month_Id = MONTH(GETDATE()))

Logic - To add up the sum of expenses in Sept 2012, 2011, 2010, ect and divide by the number of years to get my Average.

BUT how do I do this in a SQL query. Is it possible?

Disclaimer - I am pretty new at SQL.

SELECT MONTH(Date), sum(Expenses), avg(Expenses)
FROM S1_Rpt_Daily_Totals
GROUP BY MONTH(Date);

But I'm not sure what is definition of your table - I only guessed from given SQL.

Assuming you are using SQL Server 2005+ you should be able to use this:

;with a(sumexpenses, [month])
as
(
select  SUM(Expenses)
        ,DATEADD(month, datediff(month,0,[Date]), 0)
from    S1_Rpt_Daily_Totals
group by 
        DATEADD(month, datediff(month,0,[Date]), 0)
)

select  a1.[month]
        ,a1.sumexpenses
        ,AVG(a2.sumexpenses) as average
from    a a1
join    a a2
    on  MONTH(a1.[month]) = MONTH(a2.[month])
group by 
        a1.[month]
        ,a1.sumexpenses

This solution only uses the Date, so if it works you might get rid of month_id and date_year.

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