带SUM()的SQL转换为LINQ

时间:2017-02-17 18:59:34

标签: c# sql linq

我有这个sql并想将其转换为linq。 sql使用SUM合并db中的列,我想在linq中执行相同的操作:

SELECT 
[company]
  ,[employeeid]
  ,[year]
  ,[period]
  ,[project]
  ,[activity]
  ,SUM(hours1) as day1
  ,SUM(hours2) as day2
  ,SUM(hours3) as day3
  ,SUM(hours4) as day4
  ,SUM(hours5) as day5
  ,SUM(hours6) as day6
  ,SUM(hours7) as day7
  ,[projecttype]
  ,[runtableid]  
FROM ExportHoursToERP 
where runtableid = 6090
group by [company], [employeeId],[year],[period],[project],[activity],[projecttype],[runtableid]

这是我迄今为止没有成功的尝试:

var DbRows = from r in dal.ExportHoursToERPs
              where r.runtableid.Equals(6090)
              group r by new { r.company, r.employeeid, r.year, r.period, r.project, r.activity, r.projecttype, r.runtableid } into og
              select new
              {
                  company = r.company,
                  Employee = r.employee,
                  Year = r.year,
                  WeekNo = r.period,
                  Project = r.project,
                  Activity = r.activity,
                  day1 = og.Sum(y => y.hours1)
                  day2 = og.Sum(y => y.hours2)
                  day3 = og.Sum(y => y.hours3)
                  day4 = og.Sum(y => y.hours4)
                  day5 = og.Sum(y => y.hours5)
                  day6 = og.Sum(y => y.hours6)
                  day7 = og.Sum(y => y.hours7)
                  ProjectType = r.projecttype,
                  RuntableId = r.runtableid
              };

1 个答案:

答案 0 :(得分:0)

而不是这个

company = r.company

使用它:

company = og.Key.company

那是因为您想要访问属于分组键的属性。
当然,您需要为属于分组对象的所有属性应用相同的系统