Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Find row with max value for each key

I have a table stored in SQL Server which I hope to query using LINQ. A vague description of the table:

  ID1  |  ID2  |  SomeData
-----------------------------
   1   |   1   |  'Moo'
   1   |   2   |  'Meow'
   1   |   3   |  'Woof'
   1   |   4   |  'Cheap'
   2   |   1   |  'Quack'
   2   |   2   |  'Grrrrr'
   2   |   3   |  'Wan wan'

I am only interested in rows where ID2 is the greatest value per ID1 Example desired results:

   1   |   4   |  'Cheap'
   2   |   3   |  'Wan wan'

I have come up with this SQL code:

SELECT *
FROM SomeTable a
INNER JOIN
(
    SELECT ID1, MAX(ID2) as SomeName
    FROM SomeTable
    GROUP BY ID1
) as b
ON a.ID1 = b.ID1 and a.ID2 = b.SomeName

When implementing in LINQ, is it also require to have a sub query? That is, query the database and load a variable with the 'inner query' results, then query the same table but compare against values from the 'inner query'? I know if I tinker with this for a while, I'll get it eventually, but I feel like there is probably some fancy way to do this in LINQ really easily.

Desired answer will utilize extension method syntax.

Bonus: Is there any type of standard LINQ syntax to extension method syntax converter? What tools do you guys use to play with LINQ statements? It seems a little cumbersome to me to require an entire c# (ASP.NET MVC for me) to play with a LINQ query.

like image 591
Jeff Avatar asked Feb 07 '13 19:02

Jeff


1 Answers

The straight forward way:

var result = db.SomeTable.GroupBy(x => x.ID).Select(g => g.OrderByDescending(x => x.ID2).First());

Not entirely sure how efficient SQL this translates to, so if that is important, check it with your favorite profiler !

like image 193
driis Avatar answered Nov 01 '22 13:11

driis