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 2005 Forums
 Transact-SQL (2005)
 Calculate Average Change

Author  Topic 

ejbatu
Starting Member

21 Posts

Posted - 2010-07-16 : 16:39:51
Hi,

How can I find the average changes for each client using the data below; for example, if we take client 100:
The change from 2/2010 and 3/2010 is 1.27
The change from 3/2010 and 4/2010 is 1.12
The change from 4/2010 and 5/2010 is 0.35
The change from 5/2010 and 6/2010 is -16
The change from 6/2010 and 7/2010 is 1.75

Then calculate the average excluding any negative changes would be: 1.1225
Rounded to 1.12 to be displayed

For Client 101 the change from 6/2010 and 7/2010 is 0.7
Then the average would be (obviously) 0.7
Rounded to 0.7 to be displayed

The display would be:
ClientID	ProductName	AvrageChange
100 bfcxb 1.12
101 tkczfbag 0.7


Data
ClientID        ProductName     Size    MeasuredDate
100 bfcxb 48.38 2/1/2010
100 bfcxb 49.65 3/1/2010
100 bfcxb 50.77 4/1/2010
100 bfcxb 51.12 5/1/2010
100 bfcxb 35.12 6/1/2010
100 bfcxb 36.87 7/1/2010

101 tkczfbag 2.06 7/1/2010
101 tkczfbag 1.36 6/1/2010

slimt_slimt
Aged Yak Warrior

746 Posts

Posted - 2010-07-17 : 04:51:53
try this:


create table ejb
(clientID int
,ProductName varchar(10)
,size float
,Date smalldatetime)

insert into ejb
select 100,'bfc',48.38,'2010/01/02' union all
select 100,'bfc',49.65,'2010/01/03' union all
select 100,'bfc',50.77,'2010/01/04' union all
select 100,'bfc',51.12,'2010/01/05' union all
select 100,'bfc',35.12,'2010/01/06' union all
select 100,'bfc',36.87,'2010/01/07' union all
select 101,'bdd',2.06,'2010/01/07' union all
select 101,'bdd',1.36,'2010/01/06'

--(8 row(s) affected)

select
x.clientID
,avg(DIFF) as avg_DIFF
from
(
select
-- e2.size
-- ,e2.date
-- ,e1.size
-- ,e1.date
DIFF=e2.size - e1.size
,e1.clientID
from ejb as e1
join ejb as e2
on e1.clientID = e2.clientid and e1.date = e2.date+1
) as x

group by x.clientID
order by x.clientID
Go to Top of Page

Sachin.Nand

2937 Posts

Posted - 2010-07-17 : 05:12:45
OR

select ClientID,ProductName,round(avg(avgs),2)AverageChange
from
(
select *,(Size-(select Size s1 from yourtbl t2 where t1.MeasuredDate=DATEADD(dd,1,t2.MeasuredDate) and t1.ClientID=t2.ClientID))as avgs from yourtbl t1
)t
where avgs>=0 group by MeasuredDate,ProductName





Limitations live only in our minds. But if we use our imaginations, our possibilities become limitless.

PBUH
Go to Top of Page

ejbatu
Starting Member

21 Posts

Posted - 2010-07-20 : 14:48:08
Thank you
Go to Top of Page
   

- Advertisement -