Click here to monitor SSC
SQLServerCentral is supported by Red Gate Software Ltd.
 
Log in  ::  Register  ::  Not logged in
 
 
 
        
Home       Members    Calendar    Who's On


Add to briefcase

Average Value based previous record Avg Value Expand / Collapse
Author
Message
Posted Tuesday, October 09, 2012 9:16 PM
SSC Journeyman

SSC JourneymanSSC JourneymanSSC JourneymanSSC JourneymanSSC JourneymanSSC JourneymanSSC JourneymanSSC Journeyman

Group: General Forum Members
Last Login: Thursday, May 16, 2013 3:26 AM
Points: 84, Visits: 645
Hi Experts,

Here is another scenario,th some sampe data
CREATE TABLE #sample
(
id int identity ,
weight float
)

insert into #sample
select 10 union all
select 30 union all
select 20 union all
select 50.5 union all
select 100 union all
select 81

select * from #sample

-- e
expected output:

I need to calculate the average of weight based on previous records Avg value.

formula for avg_current_prevoius is (previous average value+current weight value)/2.0

id	weight   avg_current_prevoius     
1 10 10
2 30 20
3 20 20
4 50.5 35.2500
5 100 67.225
6 81 74.312500

Please help me ..
Post #1370658
Posted Tuesday, October 09, 2012 10:17 PM


Ten Centuries

Ten CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen CenturiesTen Centuries

Group: General Forum Members
Last Login: 2 days ago @ 12:58 AM
Points: 1,169, Visits: 1,244
Here is the query:

;WITH tempavg
AS (SELECT id,
weight,
weight avg_current_prevoius
FROM #sample
WHERE id = 1
UNION ALL
SELECT a.id,
a.weight,
.5 * ( a.weight + b.avg_current_prevoius )
FROM #sample a
INNER JOIN tempavg b
ON b.id + 1 = a.id)
SELECT *
FROM tempavg;



~ Lokesh Vij

Guidelines for quicker answers on T-SQL question
Guidelines for answers on Performance questions

Link to my Blog Post --> www.SQLPathy.com

Follow me @Twitter

Post #1370665
« Prev Topic | Next Topic »

Add to briefcase

Permissions Expand / Collapse