Get distinct columns with order by date
I have these following two tables:
Job Title | PostDate | CompanyId
As开发者_如何学Gositant | 12/15/10 | 10
Manager | 12/1/10 | 11
Developer | 12/31/10 | 10
Assitant | 12/1/10 | 13
PM | 11/29/10 | 12
CompanyId | Name
10 | Google
11 | Yahoo
12 | Microsoft
13 | Oracle
Now i would like to get 3 different companies with the jobs sorted by post date. The result table would be following:
Job Title | PostDate | CompanyName
Developer | 12/31/10 | Google
Manager | 12/1/10 | Yahoo
Assitant | 12/1/10 | Oracle
How can I achieve that using a linq query? Any help will be appreciated...
I think that would be something like:
var query = from company in db.Companies
join job in db.Jobs on company.CompanyId equals job.CompanyId
group job by company into jobsByCompany
let lastJob = jobsByCompany.OrderByDescending(x => x.PostDate)
.First()
orderby lastJob.PostDate descending
select new
{
JobTitle = lastJob.JobTitle,
PostDate = lastJob.PostDate,
CompanyName = jobsByCompany.Key.Name
};
It's a little odd to do a join and then a group - we could do a GroupJoin instead, but then discard empty options:
var query = from company in db.Companies
join job in db.Jobs on company.CompanyId equals job.CompanyId
into jobsByCompany // Make this a group join
let lastJob = jobsByCompany.OrderByDescending(x => x.PostDate)
.FirstOrDefault()
where lastJob != null
orderby lastJob.PostDate descending
select new
{
JobTitle = lastJob.JobTitle,
PostDate = lastJob.PostDate,
CompanyName = company.Name
};
EDIT: Note that doesn't just take the top three results. Use query = query.Take(3);
to just get the first three results.
精彩评论