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)
 Select top X items for each category

Author  Topic 

codewzrd
Starting Member

8 Posts

Posted - 2005-06-28 : 11:51:47
A while back I had posted a question to this board asking how to select the top 10 items by category. See here... [url]http://www.sqlteam.com/forums/topic.asp?TOPIC_ID=49173&SearchTerms=top,10[/url]

For a while this worked fine. But now I'm selecting the top 500 items for each category. The query I am using takes over an hour to complete!

The category/item table contains 41347 records.

The way I understand correlated subqueries is that for each row returned by the outer query, the inner query gets executed. That means that I am executing the inner query (select top 500 ...) 41,347 times!

Is there a better way to do this? Otherwise I may just use cursors and select all distinct categories and then for each category select the top 500 items in that category.

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2005-06-29 : 00:34:54
Use both Query approach and Cursor method
Set the execution plan and select the one which has minimum query cost

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page

spirit1
Cybernetic Yak Master

11752 Posts

Posted - 2005-06-29 : 05:41:34
try this approach also:

Declare @myTable table (cat varchar(100), subcat varchar(100), rank int )
Insert Into @myTable
Select 'A', 'a', 2
Union All Select 'A', 'b', 52
Union All Select 'A', 'c', 14
Union All Select 'A', 'd', 46
Union All Select 'A', 'e', 37
Union All Select 'A', 'f', 95
Union All Select 'A', 'g', 73
Union All Select 'A', 'h', 67
Union All Select 'A', 'i', 80
Union All Select 'A', 'j', 03
Union All Select 'B', 'a', 18
Union All Select 'B', 'b', 44
Union All Select 'B', 'c', 52
Union All Select 'B', 'd', 60
Union All Select 'B', 'e', 28
Union All Select 'B', 'f', 06
Union All Select 'B', 'g', 70
Union All Select 'B', 'h', 90
Union All Select 'B', 'i', 89

Union All Select 'B', 'j', 31
declare @n int
Set @n = 500
Select Cat, subCat, rank
From @myTable as A
Where (Select count(*) From @myTable Where cat=A.cat and rank <= A.rank)<=@n
Order By Cat, Rank Desc


but selecting first 500 per category won't be very fast either way.

Go with the flow & have fun! Else fight the flow
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2005-06-29 : 08:02:41
quote:
but selecting first 500 per category won't be very fast either way.


Yes thats true

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -