[英]LINQ join and group
I'm new to LINQ, and I'm trying to convert this SQL query into its LINQ equivalent: 我是LINQ的新手,并且正在尝试将此SQL查询转换为LINQ等效项:
select S.*
from Singles S
join (
select max(SingleId) as SingleId
from Single
group by ArtistId) S2 on S2.SingleId = S.SingleId
order by Released desc
The table looks like this: 该表如下所示:
-----------
| Singles |
|-----------|
| SingleID |
| ArtistId |
| Released |
| Title |
| ..... |
-----------
and so on... And contains for example these items: 依此类推...并包含以下示例:
SingleID ArtistID Released Title
1 1 2011-05-10 Title1
2 1 2011-05-10 Title2
3 2 2011-05-10 Title3
4 3 2011-05-10 Title4
5 4 2011-05-10 Title5
6 2 2011-05-10 Title6
7 3 2011-05-10 Title7
8 5 2011-05-10 Title8
9 6 2011-05-10 Title9
So I'm trying to get the latest singles, but only one per artist. 因此,我正在尝试获取最新的单曲,但每位艺术家只有一首。 Could anyone help me?
有人可以帮我吗? :) Maybe there's even a better way to write the query?
:)也许还有更好的方式编写查询?
To answer the questions posted in the comments: We're using Microsoft SQL Server, and LINQ to NHibernate. 要回答评论中发布的问题:我们正在使用Microsoft SQL Server和LINQ to NHibernate。
Here's a sample that we're using right now, that returns the latest singles, without grouping by artistid: 这是我们目前正在使用的示例,该示例将返回最新的单曲,而无需按artistid进行分组:
public Single[] GetLatest()
{
IQueryable<Single> q;
q = from s in _sess.Query<Single>()
where s.State == State.Released
orderby s.Released descending
select s;
return q.Take(20).ToArray();
}
How about this: 这个怎么样:
var firstSingles = Singles.GroupBy(x => x.ArtistId)
.Select(g => g.OrderByDescending(x => x.Released).First())
.ToList();
Something like this should work. 这样的事情应该起作用。
var query = from s in db.Singles
group s by s.ArtistID into sg
let firstSingle = sg.OrderByDescending(r => r.SingleID).FirstOrDefault()
select new
{
ArtistID = sg.Key,
SingleID = firstSingle.SingleID,
Released = firstSingle.Released,
Title = firstSingle.Title,
}
singles
.OrderByDescending(s => s.SingleID)
.GroupBy(s => s.SingerID, (id, s) => new
{
SingleID = id,
Title = s.First().Title
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.