Linq在多个字段上加入并分组,并截断日期

时间:2018-05-13 20:11:38

标签: c# entity-framework linq

我有以下Sql查询,它连接两个表和按日期分组和用户ID

用户表

UserName UserId

LookupScannedHistory

HistoryId UserId ScannedDate ScannedCount

我已经编写了以下sql查询来连接表和group by userId和扫描日期删除Time varaint

SELECT 
      l.[UserID]
      ,CAST([ScannedDate] AS DATE)
      ,Sum([ScannedCount])
      ,[UserName]
  FROM [dbo].[LookupScannedHistory] l
  Join [dbo].[UserMaster] u
  on l.UserID = u.UserId
  group by l.UserId, u.UserName, CAST([ScannedDate] AS DATE)

我想将其转换为linq。

我试过这个

 (from log in dataContext.LookupScannedHistories
          join user in dataContext.UserMasters
          on log.UserID equals user.UserId 
          where log.ScannedDate >= fiveDayPriorDate
           orderby log.ScannedDate
           group log by new
           {
           ScannedDateOnly = EntityFunctions.TruncateTime(log.ScannedDate),
           log.UserID
           } into dateClickedHistory

          select dateClickedHistory                                                                  
        ).ToList();

我这样做了这给了我想要的但我无法通过组合加入和分组来包含用户名

1 个答案:

答案 0 :(得分:0)

我找到了解决方案。

var usersReportGroupList = (from log in dataContext.LookupScannedHistories
                            join user in dataContext.UserMasters
                            on log.UserID equals user.UserId 
                            where log.ScannedDate >= fiveDayPriorDate
                            orderby log.ScannedDate
                             group new { user.UserName, log.ScannedCount, 
                              log.ScannedDate} 

                              by new
                              {
                               ScannedDateOnly = 
                             EntityFunctions.TruncateTime(log.ScannedDate),
                             log.UserID,
                             user.UserName
                             } 
                             into dateClickedHistory
                              select dateClickedHistory                                              
                             ).ToList();
   var usersReportList = new List<LookupScannedHistoryDetails>();
                    foreach (var group in usersReportGroupList)
                    {
                        usersReportList.Add(new LookupScannedHistoryDetails()
                        {
                            ScannedCount = group.Sum(x => x.ScannedCount.Value),
                            ScannedDate = group.Key.ScannedDateOnly.Value,
                            UserId = group.Key.UserID.Value,
                            UniqueCount = group.Count(),
                            UserName = group.Key.UserName
                        });
                    }