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 2000 Forums
 Transact-SQL (2000)
 Nearest Match

Author  Topic 

Scott
Posting Yak Master

145 Posts

Posted - 2004-08-05 : 02:28:35
I have the following table:

Cat | Rank | Value
A 1 11
A 2 12
A 3 14

I am wanting to group the Cat field and get the average value, I then want assign the rank value that most closely matches the avg.

ie: In the above my select would return:

Cat | Rank | Avg
A | 2 | 12.3


Thanks
Scott

mr_mist
Grunnio

1870 Posts

Posted - 2004-08-05 : 03:36:20
You could probably simplify -


set nocount on

create table #moo (cat varchar(1), rank int, value real)

insert into #moo values ('a',3,14)
insert into #moo values ('a',2,12)
insert into #moo values ('a',1,11)
insert into #moo values ('b',1,44)


select d.cat, d.rank, f.avgr from
(
select a.cat, a.rank, value - avgr as diff from #moo a
inner join
(select cat, avg(value) as avgr from #moo group by cat) b
on a.cat = b.cat
) d
Inner join
(
select cat, min(diff * diff) as unsigneddiff from
(
select a.cat, a.rank, value - avgr as diff from #moo a
inner join
(select cat, avg(value) as avgr from #moo group by cat) b
on a.cat = b.cat
) b
group by cat) e
on d.diff * d.diff = unsigneddiff
and d.cat = e.cat

inner join
(select cat, avg(value) as avgr from #moo group by cat)
f
on d.cat = f.cat

drop table #moo


-------
Moo. :)
Go to Top of Page

mohdowais
Sheikh of Yak Knowledge

1456 Posts

Posted - 2004-08-05 : 04:48:35
Do you need to do this for every category? Building on your example:


declare @TempTable table
(cat varchar(1), rank int, value numeric(9,2))

insert into @TempTable values ('A',1,11)
insert into @TempTable values ('A',2,12)
insert into @TempTable values ('A',3,14)
insert into @TempTable values ('B',1,63)
insert into @TempTable values ('B',2,55)
insert into @TempTable values ('B',3,65)

select cat,
(select top 1 rank from @TempTable b where a.cat = b.cat order by abs(a.avgval - b.value) asc) AS NearestMatch,
avgval from
(
select cat, avg(value) as avgval
from @TempTable
group by cat
) a

Looks too simplistic compared to mr. moo's, hope I am not missing something obvious.

OS
Go to Top of Page

mr_mist
Grunnio

1870 Posts

Posted - 2004-08-05 : 06:18:31
abs. That's the function I was looking for to avoid the whole diff * diff thing.

Yours is much simpler :D

-------
Moo. :)
Go to Top of Page
   

- Advertisement -