I want to perform a simple sql query but cannot manage to get it right.
(Sorry for the example, that’s all I could think of to illustrate my problem)
Let’s say I have a table FooBar that contains X columns, but only 3 columns that are useful to me.
DogKind_Id, FoodQuantity, Day_Id
And I want to know, for each DogKind_Id, what was the day where the FoodQuantity was the maximum !
So for a FooBar table like :
DogKind_Id, FoodQuantity, Day_Id
1,2, 2
1,10,1
1,4,5
2,3, 3
2,9,1
2,87,5
3,0, 3
3,0,2
3,1,6
The result of my query will be :
DogKind_Id, Day_Id
1,1
2,5
3,6
So far, I succeeded in doing this :
SELECT DogKind_Id, MAX(FoodQuantity)
FROM FooBar
GROUP BY DogKind_Id
But I cannot manage to simply use this result to get the Day_Id… If I had Day_Id in the above SELECT, it adds up lots of rows… I tried SUBSELECT, EXISTS but obviously doing it wrong !
Can you guys help me a bit ?
basically, the inner query is your version, which gets the id/max values.
You then have the outer query joining against this subquery to figure out WHICH of the records has that max foodquantity, so you can get the associated dayid