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.
| Author |
Topic |
|
amodi
Yak Posting Veteran
83 Posts |
Posted - 2011-01-19 : 01:50:25
|
| Dear Friends,I want top 5 of each modelId, the table is as follows:Id------ ModelId3001------ abc3002------ abc3003------ xyz3004------ xyz3005------ xyz3006------ xyz3007------ xyz3008------ xyz3009------ xyz3010------ xyz3011------ xyz3012------ ppp3013------ ppp3014------ ppp3015------ ppp3016------ ppp3017------ ppp3018------ ppp3019------ ppp3020------ ppp3021------ abc3022------ abc3023------ abc3024------ abc3025------ abc3026------ abc3027------ abcExpected Output: Id------ ModelId3001------ abc3002------ abc3021------ abc3022------ abc3023------ abc3003------ xyz3004------ xyz3005------ xyz3006------ xyz3007------ xyz3012------ ppp3013------ ppp3014------ ppp3015------ ppp3016------ pppIn a real world senario i need to fetch "top 20" and actaul table contains more than 50,000 records, so needs to take care of performance also. Thanks in Advance. |
|
|
khtan
In (Som, Ni, Yak)
17689 Posts |
Posted - 2011-01-19 : 02:17:23
|
hopefully you are using SQL 2005 /2008select *from( select *, row_no = row_number() over (partition by ModelId order by Id) from yourtable) dwhere d.row_n <= 5 KH[spoiler]Time is always against us[/spoiler] |
 |
|
|
lionofdezert
Aged Yak Warrior
885 Posts |
Posted - 2011-01-19 : 06:23:42
|
| Use Common Table Expression for such problemsWITH CTE_TABLEAs (SELECT ID,ModelId,ROW_NUMBER() OVER (ORDER BY ID) AS RowNUm FROM YourTableNameHere)SELECT * FROM CTE_TABLE WHERE RowNUm <=5--------------------------http://connectsql.blogspot.com/ |
 |
|
|
amodi
Yak Posting Veteran
83 Posts |
Posted - 2011-01-19 : 07:44:37
|
| Excuse me for delayed feeback.Thanks a million khtan!Thanks lionofdezert |
 |
|
|
|
|
|