How to Select the TOP n Rows For Each Group in Queryspec

Posts   
 
    
gregkuha60
User
Posts: 47
Joined: 23-Jan-2012
# Posted on: 07-Mar-2014 13:07:51   

Hello I'm struggling with how to make this T-SQL to a Queryspec equivalent. This is a example from http://archive.msdn.microsoft.com/SQLExamples/Wiki/View.aspx?title=SelectTopNByGroup.

There are Multiple Rows for Each Category, and there is a desire to SELECT ONLY the TOP two (2) Rows per Category by Price.

Query to Retrieve Desired Data

SELECT DISTINCT   RowID,   Category,   [ID],   [Description], Price
FROM @MyTable t1
WHERE RowID IN (SELECT TOP 2 RowID FROM @MyTable t2
                WHERE t2.Category = t1.Category ORDER BY Price DESC  )
ORDER BY   Category,  Price DESC

Any help would be appreciated. Thanks Greg

Walaa avatar
Walaa
Support Team
Posts: 14950
Joined: 21-Aug-2005
# Posted on: 07-Mar-2014 14:48:01   

The In predicate is produced by using the FieldCompareSetPredicate