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 Administration (2000)
 How do i....

Author  Topic 

jayp369
Starting Member

26 Posts

Posted - 2007-01-22 : 12:44:09
i am trying to create a query that returns the top 5 records of each id in a single table (without using a cursor).

Does anyone have an idea on how to do this?

Jay

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2007-01-22 : 13:02:03
What is the other column, besides id?


Peter Larsson
Helsingborg, Sweden
Go to Top of Page

jayp369
Starting Member

26 Posts

Posted - 2007-01-22 : 13:30:35
Subject, Desc and DateTime

Jay
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2007-01-22 : 13:41:34
Ok, now when we know that, how do you define "top 5"? Top 5 according to what?


Peter Larsson
Helsingborg, Sweden
Go to Top of Page

jayp369
Starting Member

26 Posts

Posted - 2007-01-22 : 13:58:12
By Datetime

Jay
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2007-01-22 : 14:05:17
ascending or descending?


Peter Larsson
Helsingborg, Sweden
Go to Top of Page

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2007-01-22 : 14:11:50
[code]-- prepare sample data
declare @s table ([id] int, [subject] varchar, [desc] varchar(2), [dt] datetime)

insert @s
select 1, 'a', 'aa', '20060101' union all
select 1, 'a', 'aa', '20060102' union all
select 1, 'a', 'aa', '20060103' union all
select 1, 'a', 'aa', '20060104' union all
select 1, 'a', 'aa', '20060105' union all
select 1, 'a', 'aa', '20060106' union all
select 1, 'a', 'aa', '20060107' union all
select 1, 'a', 'aa', '20060108' union all
select 1, 'a', 'aa', '20060109' union all
select 1, 'a', 'aa', '20060110' union all
select 1, 'a', 'aa', '20060111' union all
select 2, 'b', 'bb', '20070101' union all
select 2, 'b', 'bb', '20070102' union all
select 2, 'b', 'bb', '20070103' union all
select 2, 'b', 'bb', '20070104' union all
select 2, 'b', 'bb', '20070105' union all
select 2, 'b', 'bb', '20070106' union all
select 2, 'b', 'bb', '20070107' union all
select 2, 'b', 'bb', '20070108'

-- show one result with highest 5
select s.*
from @s as s
where (select count(*) from @s w where w.id = s.id and w.dt >= s.dt) <= 5

-- show result with lowest 5
select s.*
from @s as s
where (select count(*) from @s w where w.id = s.id and w.dt <= s.dt) <= 5[/code]

Peter Larsson
Helsingborg, Sweden
Go to Top of Page
   

- Advertisement -