| Author |
Topic |
|
jeffbond
Starting Member
16 Posts |
Posted - 2009-01-14 : 16:29:39
|
| Hi,I have a query that returns 3 columns and several rows:year, week, valueex:2008,52,102008,53,72009,1,992009,2,3I need a fourth column that would return the average of the sum of the 3 past weeks....ex: last row in the example above would be: 2009,2,3,38.66(10+7+99)/3 = 38.66here is my sql so far:select convert(char(4), td.date, 120) as year, datepart("ww",td.date) as weekN, count(td.value) as valuefrom mytable tdwhere td.date >= @startdateand td.date < @enddategroup by convert(char(4), td.date, 120), datepart("ww",td.date)order by year asc, weekN asc |
|
|
sakets_2000
Master Smack Fu Yak Hacker
1472 Posts |
Posted - 2009-01-14 : 16:42:02
|
| Have a look at this,http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=117395&SearchTerms=average |
 |
|
|
Vinnie881
Master Smack Fu Yak Hacker
1231 Posts |
Posted - 2009-01-14 : 17:12:47
|
Here's one method. On records that have < 3 prior records it will go back as far as it can.Declare @T table ([year] int,[week] int,[value] int)Insert Into @Tselect 2008,52,10 Union allselect 2008,53,7 Union allselect 2009,1,99 Union allselect 2009,2,3 Union allselect 2009,6,1 Union allselect 2008,22,10Select *,coalesce((Select Avg(aa.[Value]) as [Value]from ( Select Row_Number() over (Order by aaa.[Year] DESC,aaa.[Week] DESC) as ROWID,convert(decimal(10,4),aaa.[Value]) as [value] from @T aaa where convert(decimal(10,0),convert(varchar(4),aaa.[year]) + ISNULL(REPLICATE('0', 2 - len(ISNULL(convert(varchar(2),aaa.[week]) ,0))), '') + convert(varchar(2),aaa.[week])) < convert(decimal(10,0),convert(varchar(4),a.[year]) + ISNULL(REPLICATE('0', 2 - len(ISNULL(convert(varchar(2),a.[week]) ,0))), '') + convert(varchar(2),a.[week])) ) aa where aa.ROWID <= 3),0) as Averagefrom @T aorder by a.[Year],a.[Week] Success is 10% Intelligence, 70% Determination, and 22% Stupidity.\_/ _/ _/\_/ _/\_/ _/ _/- 881 |
 |
|
|
|
|
|