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
 SQL Server Development (2000)
 SUM TOP n values

Author  Topic 

AskSQLTeam
Ask SQLTeam Question

0 Posts

Posted - 2002-03-25 : 08:29:08
Matt writes "I have a table with competitors IDs and their points results for various events throughout the year. Now i need to generate a ranking list which uses only the best n results for each competitor.

For example assume i have the data below and the ranking list should take into account the best 2 results

Competitor Points
1 1
1 2
1 3
2 6
2 7
2 8
3 8


I need a query that would be able to give the following results:

Pos. Competitor Total
1 2 15
2 3 8
3 1 5

An added bonus would be the ability to consider the next best result in case of a tie but i'm totally stuck on the first part of the problem.

I'm using SQL Server 2000 on windows 2000

Thanks for any help you can give"

setbasedisthetruepath
Used SQL Salesman

992 Posts

Posted - 2002-03-25 : 08:38:49
this ought to do it:


create table #temp
(
competitor int,
points int
)

create table #results
(
pos int identity(1,1),
competitor int,
total int
)

insert #temp ( competitor, points )
select 1, 1 union
select 1, 2 union
select 1, 3 union
select 2, 6 union
select 2, 7 union
select 2, 8 union
select 3, 8

insert #results ( competitor, total )
select competitor, sum(points)
from #temp t
where not exists (
select 1
from #temp
where competitor = t.competitor and points > t.points
group by competitor
having count(*) > 1 )

group by competitor
order by sum(points) desc

select * from #results


setBasedIsTheTruepath
<O>
Go to Top of Page
   

- Advertisement -