1

I have the following data in sql server table:

EmployeeId ForMonth ForYear Value 1 1 2015 45000.00 1 6 2015 35000.00 1 12 2014 66666.00 2 1 2015 70000.00 2 5 2015 80000.00 

I need to find the LINQ-to-SQL query to select for each EmployeeId the record having max ForMonth and max ForYear. So the result should be:

EmployeeId ForMonth ForYear Value 1 6 2015 35000.00 2 5 2015 80000.00 

It's not that I didn't try to solve this before coming and posting this question, but the problem is that I didn't know how to write this query in SQL server, so I don't have any LINQ code to add. Please if you find this a bad question, ask me to delete it.

4
  • I have a dream that down voters start to have the kindness to say at least why did they down voted a question and caused points loss for a user :/ Commented Jul 6, 2015 at 15:34
  • Of course I tried, but I have no decent code to post, I have a problem in figuring out how to write the query in sql server, so I don't have something to write in LINQ. Commented Jul 6, 2015 at 15:36
  • Ok I'll try and update my question with what I get, Or would you recommend to delete it for now? Commented Jul 6, 2015 at 15:40
  • try solution in answer ... Commented Jul 6, 2015 at 15:52

2 Answers 2

2

You only want 1 record per employee, so you need to group by the ID. Then you order your groups by the lastest year/month and select the first one

var query = from e in db.Employees group e by e.EmployeeId into g select g.OrderByDescending(e => e.ForYear) .ThenByDescending(e => e.ForMonth) .FirstOrDefault(); 
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot for this elegant and simple solution!
0

I am assuming you want the record with the greatest ForYear and greatest ForMonth

var result = (from db in MYDBContext orderby db.ForYear descending, db.ForMonth descending select db).First(); 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.