I want to calculate the sum and average of my data in the past 24 months how can I achieve that? In my database I have 1000 records with the field (ID, Store_ID, Date, Sales) I want to calculate the average of all my data from THIS month up to the last 24 months.
I believe you are looking for the DATEADD
function. Here is the documentation .
Essentially, you will use a where condition to check if a date is older than a certain date.
By using the DATEADD
function with the current time, you can create a date X months in the past.
SELECT columns FROM table WHERE date < DATEADD(month, numberOfMonths, GETDATE());
For SQL querys that use aggregate functions (such as SUM
), depending on how you use the function you may require the HAVING
clause; instead of, the WHERE
clause. I don't think your case will require this; but, I may be wrong.
You can read more on HAVING vs WHERE
at this article .
Here is an example:
SELECT columns FROM table HAVING date < DATEADD(month, numberOfMonths, GETDATE());
The code samples are untested; however, the general structure is there. We are also using the GETDATE()
function to get the current database date.
Please find below SQL where I am getting last 12 month sum of members for a given group in X table.
You can use the similar approach with some modification to below code snippet as per actual table structure to find out desired result set.
;with tbl1
as
(
select MonthID,count(MemberID) as RecCount from MemberTable a with (nolock) group by MonthID
)
,tbl2
as
(
select
ROW_NUMBER() OVER(order by MonthID) as RowID
,MonthID
,sum(RecCount) over(order by MonthID ROWS BETWEEN 11 PRECEDING and CURRENT ROW) as [SumLast12Months]
from tbl1
)
select * from tbl2 where RowID>=12 -- Before RowID 12 none of the month has complete 12 month rollup
Here are a couple of other options:
select sum(Sales) as [Total Sales], avg(Sales) as [Average Sales]
from (select * from @tbl where dt >= dateadd(mm, -24, getdate())) as foo
or
with CTE
as
(
select * from @tbl where dt >= dateadd(mm, -24, getdate())
)
select sum(Sales) as [Total Sales], avg(Sales) as [Average Sales] from CTE
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.