tags:

views:

33

answers:

2

If I have a table of fruits:

FruitId ColorId NumofPurchased.

I want to return a row for each of the colorId's where NumOfPurchased is max for that colorId. I am coming up with approaches like looping through the colorId's or manually write 10 queries for 10 colors ... I don't know, is there a better/more optimized way to do this?

I am using SQL Server 2008 express.

+1  A: 
SELECT MAX(NumOfPurchased), ColorId, FruitId
FROM fruit
GROUP BY ColorId, FruitId

That should do the trick.

jwiscarson
I need fruitid too in the select clause, which will break the code because it's not in the group by clause or anything.
progtick
Edited my answer to include this column.
jwiscarson
then it will list all the fruits in the result (I just checked)! I want to select the fruit with max numberofpurchased per each color.
progtick
That's a different set of requirements than what you originally stated in the question. You could try removing ColorId from the SELECT to see how that affects your resultset.
jwiscarson
A: 

Not sure if this is exactly what you want (whether it's the max for each colour across all fruit, or the max for each colour per fruit) - but you can change/add values to the PARTITION BY clause if necessary.

;with fruitCTE
AS
(
    SELECT  FruitId, ColorId, NumofPurchased,
            ROW_NUMBER() OVER (PARTITION BY ColorId,
                               ORDER BY NumofPurchased DESC
                              ) AS rn
    FROM    fruit
)
SELECT FruitId, ColorId, NumofPurchased,
FROM fruitCTE
WHERE rn = 1;
Ed Harper