Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 SQL Server 2012 Forums
 Transact-SQL (2012)
 Monthly Average Based On Total Summary

Author  Topic 

wdysc
Starting Member

2 Posts

Posted - 2013-07-19 : 12:56:14
I have a scenario where I need to get the average monthly income based on a period passed in by the user,

Here is my basic table structure

ID, MyDate, MyAmount
1, 5/1/2013, 15.00
2, 5/11/2013, 30
3, 5/29/2013, 10.00
4, 6/1/2013, 12.00
5, 6/3/2013, 25.00
6, 6/4/2013, 13.00
7, 6/7/2013, 18.00
8, 6/11/2013, 30.00
9, 7/2/2013, 45.00
10, 7/5/2013, 1.00


I need to know based on my total amount how much is the average for each month based on the total summary.
I know I can get the actual amount by grouping, but this is not the number I need. I need to know if the total is so and so, and my average is by month, I have to divide the total by the number of month and that's my average. My problem is if the period is only starting from begining of month or ending inmiddle of month, I cannot count it as a full month, therefore my average per month should not be divided by the full month.

Any approach for this...

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2013-07-19 : 13:52:37
What is the result you want for the sample data above?


N 56°04'39.26"
E 12°55'05.63"
Go to Top of Page

wdysc
Starting Member

2 Posts

Posted - 2013-07-19 : 13:56:04
The result is a single scalar amount of average per month, not broken down for each month
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2013-07-20 : 08:49:51
And how have you decided what is the average value for each month?


N 56°04'39.26"
E 12°55'05.63"
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2013-07-20 : 08:50:15
[code]SELECT SUM(MyAmount) * 1.0/COUNT(DISTINCT DATEDIFF(mm,0,MyDate))
FROM Table
[/code]

------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/
https://www.facebook.com/VmBlogs
Go to Top of Page
   

- Advertisement -