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 LarssonHelsingborg, Sweden |
 |
|
jayp369
Starting Member
26 Posts |
Posted - 2007-01-22 : 13:30:35
|
Subject, Desc and DateTimeJay |
 |
|
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 LarssonHelsingborg, Sweden |
 |
|
jayp369
Starting Member
26 Posts |
Posted - 2007-01-22 : 13:58:12
|
By DatetimeJay |
 |
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2007-01-22 : 14:05:17
|
ascending or descending?Peter LarssonHelsingborg, Sweden |
 |
|
SwePeso
Patron Saint of Lost Yaks
30421 Posts |
Posted - 2007-01-22 : 14:11:50
|
[code]-- prepare sample datadeclare @s table ([id] int, [subject] varchar, [desc] varchar(2), [dt] datetime)insert @sselect 1, 'a', 'aa', '20060101' union allselect 1, 'a', 'aa', '20060102' union allselect 1, 'a', 'aa', '20060103' union allselect 1, 'a', 'aa', '20060104' union allselect 1, 'a', 'aa', '20060105' union allselect 1, 'a', 'aa', '20060106' union allselect 1, 'a', 'aa', '20060107' union allselect 1, 'a', 'aa', '20060108' union allselect 1, 'a', 'aa', '20060109' union allselect 1, 'a', 'aa', '20060110' union allselect 1, 'a', 'aa', '20060111' union allselect 2, 'b', 'bb', '20070101' union allselect 2, 'b', 'bb', '20070102' union allselect 2, 'b', 'bb', '20070103' union allselect 2, 'b', 'bb', '20070104' union allselect 2, 'b', 'bb', '20070105' union allselect 2, 'b', 'bb', '20070106' union allselect 2, 'b', 'bb', '20070107' union allselect 2, 'b', 'bb', '20070108'-- show one result with highest 5select s.*from @s as swhere (select count(*) from @s w where w.id = s.id and w.dt >= s.dt) <= 5-- show result with lowest 5select s.*from @s as swhere (select count(*) from @s w where w.id = s.id and w.dt <= s.dt) <= 5[/code]Peter LarssonHelsingborg, Sweden |
 |
|
|
|
|