2016-11-17 120 views
1

我有下面的SQL查詢,我能夠conert到LINQ轉換SQL查詢LINQ與一組由

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

轉換爲

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

但現在我試圖拋出額外的列沒有包含在組中。我有SQL查詢

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

,但我不知道如何將它轉換到LINQ

+0

請檢查我的答案呃 – user449689

回答

0
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) 
} 
+1

g.key'上有'g'嗎? –

+0

是g不存在在這裏,也沒有在新的 – Monzingo

+0

c也添加DateTime.Now以取代Current_Timestamp – Monzingo

-1

我稍微修改馬格努斯的回答

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); 
+0

它如何可以downvoted當它的工作?其他答案有「鑰匙」,因爲它不是一把鑰匙,所以它不被識別。 – Monzingo

+0

'grp'具有'Key'的IGrouping':https://msdn.microsoft.com/zh-cn/library/bb344977(v=vs.110).aspx – Magnus

+0

@Monzingo請檢查我的答案 – user449689

0

在這裏你可以找到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();