简体   繁体   中英

T-SQL query to select last 3 months of data, last years month, averages of this month and average of all months

I have a table with columns Category, Date, Monthly_Revenue .

I need a query that will select Todays_Month , Last_Month , 2 months prior, Last_years_Month , average of today's month, average of all months.

This query is needed grouped by category.

Example :

Category | Sept, 2012 | Aug, 2012| Jul, 2012 | Sept, 2011 | Average of Sept | Avg all Mo

Being fairly new to SQL I still haven't got it yet. I figured see if somebody out there could take a crack at it. Thanks.

Sample data

'Burger'  '9/1/2012'   '500'
'Fries'  '10/1/2012    '300'
'Burger'  '6/1/2011'   '250'

you need something along these lines .Not the optimum solution but will give you a start .This is a static solution but it looks like you may want a dynamic solution

*not tested

 SELECT 
 Category
,[Sep 2012]=SUM(CASE WHEN YEAR(TranDate)= YEAR(GETDATE()) AND MONTH(TranDate)= MONTH(GETDATE()) THEN Amount ELSE NULL END)
,[Aug 2012]=SUM(CASE WHEN  YEAR(TranDate)= YEAR(DATEADD(month,-1,GETDATE())) AND MONTH(TranDate)= MONTH(DATEADD(month,-1,GETDATE()))  THEN Amount ELSE NULL END)
,[Jul 2012]=SUM(CASE WHEN YEAR(TranDate)= YEAR(DATEADD(month,-2,GETDATE())) AND MONTH(TranDate)= MONTH(DATEADD(month,-2,GETDATE())) THEN Amount ELSE NULL END)
,[AVG Sep 2012]=AVG(CASE WHEN YEAR(TranDate)= YEAR(GETDATE()) AND MONTH(TranDate)= MONTH(GETDATE()) THEN Amount ELSE NULL END)
,[AVG 12 months]=AVG(CASE WHEN TranDatee > CAST(DATEADD(year,-1,GETDATE()) AS DATE) THEN Amount ELSE NULL END)/12
FROM Table1
GROUP BY Category,Amount

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