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 |
|
codewzrd
Starting Member
8 Posts |
Posted - 2005-05-02 : 12:48:52
|
| I have a table that contains the Category, the Items in that category and the Count of Items bought. I would like to get the Top 10 items per category.The table structure is...ID idxCategory Item Total1 1 Bike 122 1 Scateboard 53 2 Flowers 184 2 Shrubs 5435 2 Trees 24The query I have is not quite correct...SELECT idxCategory, Item, TotalFROM tCategory e WITH (NOLOCK)WHERE Item IN ( SELECT TOP 10 Item FROM tCategory WITH (NOLOCK) WHERE idxCategory = e.idxCategory ORDER BY Total DESC )ORDER BY idxCategory, Total DESCThanks for any help. |
|
|
TG
Master Smack Fu Yak Hacker
6065 Posts |
Posted - 2005-05-02 : 13:56:24
|
| I don't see a problem. Why is it "not quite correct"?Be One with the OptimizerTG |
 |
|
|
codewzrd
Starting Member
8 Posts |
Posted - 2005-05-02 : 15:13:02
|
| Never mind. It turns out that I didn't do a sort by Item in the inner query. So the last few rows were different.Thanks for making me take a closer look at the query.The answer is...SELECT idxCategory, Item, TotalFROM tCategory e WITH (NOLOCK)WHERE Item IN(SELECT TOP 10 ItemFROM tCategory WITH (NOLOCK)WHERE idxCategory = e.idxCategoryORDER BY Total DESC, Item)ORDER BY idxCategory, Total DESC, Item |
 |
|
|
rockmoose
SQL Natt Alfen
3279 Posts |
Posted - 2005-05-02 : 15:39:11
|
This should give the top 10 per category, try it;SELECT t1.idxCategory ,t1.Item ,t1.TotalFROM tCategory t1WHERE 11 > ( SELECT COUNT(*) FROM tCategory t2 WHERE t1.idxCategory = t2.idxCategory AND t1.Total <= t2.Total ) rockmooseOk, saw that You just fixed it...Item must be Unique in tCategory for the IN clause to work properly. |
 |
|
|
|
|
|
|
|