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)
 Difference in values in each group

Author  Topic 

Sachin.Nand

2937 Posts

Posted - 2010-02-08 : 12:58:12
Hi want to find the difference between the the first value in each group with the preceding value

o/p shud be 1,a,10,10
1,a,5,-5
1,a,15,5
1,a,20,10
and so on.....

declare @tbl as table(id int identity(1,1),groups varchar(5),value int)
insert into @tbl
select 'a',10 union all
select 'a',5 union all
select 'a',15 union all
select 'a',20 union all
select 'b',10 union all
select 'b',100

I have came up with this

select * from @tbl t1
outer apply(select
top 1(groups),value
from @tbl t2
where t1.id=t2.id+1 and t1.groups=t2.groups and ???? --- this part i cant understand on how to get first value from each group

order by groups desc)t3




PBUH

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2010-02-08 : 13:02:07
i think this is enough


select t1.*,t1.value-coalesce(t3.value,0) as yourresult from @tbl t1
outer apply(select top 1 value
from @tbl t2
where t1.groups=t2.groups
order by id asc)t3

Go to Top of Page

Sachin.Nand

2937 Posts

Posted - 2010-02-08 : 13:07:22
quote:
Originally posted by visakh16

i think this is enough


select t1.*,t1.value-coalesce(t3.value,0) as yourresult from @tbl t1
outer apply(select top 1 value
from @tbl t2
where t1.groups=t2.groups
order by id asc)t3





Yeah exactly wat I wanted.
Thx a million Visakh.

PBUH
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2010-02-08 : 13:09:37
welcome
Go to Top of Page
   

- Advertisement -