简体   繁体   English

将SQL查询与组转换为LINQ

[英]Convert SQL query to LINQ with a group by

I have the below sql query that i am able to conert into LINQ 我有以下能够查询到LINQ的SQL查询

select count(*), BatchID 
from TimeSheetHeader 
group by BatchID having count(*) > 1

converts to 转换为

var duplicateBatchIDList = from c in _db.TimeSheetHeaders
                                               group c by c.BatchID into grp
                                               where grp.Count() > 1
                                               select grp;

But now i am trying to throw an extra column that isnt included in the group by. 但是现在我试图抛出一个额外的列,该列未包含在group by中。 I have the SQL query 我有SQL查询

select count(*), BatchID, TimeSheetCreationDate = min( TimeSheetCreationDate     ) 
from TimeSheetHeader 
where TimeSheetCreationDate >= CURRENT_TIMESTAMP
group by BatchID having count(*) > 1

But i am not sure how this convert over to LINQ 但是我不确定如何将其转换为LINQ

from c in _db.TimeSheetHeaders
where c.TimeSheetCreationDate >= CURRENT_TIMESTAMP
group c by c.BatchID into grp
where grp.Count() > 1
select new
{
    BatchID = grp.Key,
    Count = grp.Count(),
    TimeSheetCreationDate = grp.Min(x => x.TimeSheetCreationDate)
}

Here you can find the lambda expression version of the query: 在这里,您可以找到查询的lambda表达式版本:

var result = TimeSheetHeader
    .Where(t => t.TimeSheetCreationDate >= TIMESTAMP)
    .GroupBy(t => t.BatchID)
    .Where(g => g.Count() > 1)
    .Select(g => new 
        {
            Count = g.Count(),
            BatchID = g.Key,
            TimeSheetCreationDate = g.Min(x => x.TimeSheetCreationDate)
        })
    .ToList();

I slightly modified Magnus's answer 我稍微修改了马格努斯的答案

var duplicateBatchIDList = (from c in _db.TimeSheetHeaders
                                               group c by c.BatchID into grp
                                               where grp.Count() > 1
                                               select new
                                               {
                                                   BatchID = grp.FirstOrDefault().BatchID,                                                      
                                                   TimeSheetCreationDate = grp.Min(x => x.TimeSheetCreationDate)
                                               }).Where(x => x.TimeSheetCreationDate <= DateTime.Now);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM