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 2005 Forums
 Transact-SQL (2005)
 Select top 5 from multiple categories

Author  Topic 

trouble2
Constraint Violating Yak Guru

267 Posts

Posted - 2009-03-03 : 11:21:47
Hi I want to build a sp where I get the top 5 records for category 1 to 7, so in total, this should return 35 records.
Let's say the table looks like:

ZOMID Name Clicks Category
1 Bla 300 2
2 BlaBla 221 1
3 BlBl 121 3
5 AaAaA 234 1

So it should return the top 5 of category 1, the top 5 of category 2, etc. based on the clicks.

sakets_2000
Master Smack Fu Yak Hacker

1472 Posts

Posted - 2009-03-03 : 12:29:37
top 5 basis what?? Anyways, something like this ??
select top 5 ... from .. where category =1
union all
select top 5 ... from .. where category =2
union all
...
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2009-03-03 : 12:31:51
quote:
Originally posted by trouble2

Hi I want to build a sp where I get the top 5 records for category 1 to 7, so in total, this should return 35 records.
Let's say the table looks like:

ZOMID Name Clicks Category
1 Bla 300 2
2 BlaBla 221 1
3 BlBl 121 3
5 AaAaA 234 1

So it should return the top 5 of category 1, the top 5 of category 2, etc. based on the clicks.




SELECT ZOMID, Name, Clicks, Category
FROM
(
SELECT ROW_NUMBER() OVER (PARTITION BY Category ORDER BY ZOMID) AS Seq,ZOMID, Name, Clicks, Category
FROM Table
)t
WHERE Seq<=5
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2009-03-03 : 12:33:20
also see

http://sqlblogcasts.com/blogs/madhivanan/archive/2008/09/12/return-top-n-rows.aspx
Go to Top of Page
   

- Advertisement -