两个不同列的SUM和DISTINCT

时间:2012-11-23 18:42:11

标签: sql-server linq entity-framework entity-framework-4

我有一张表员工说出以下记录

   EmpID    Salary   Date

    10      2000     1/1/2011
    10      2000     2/1/2011
    20      2000     1/1/2011

我想计算员工总数和总薪水(基于其他一些参数)

是否有一种简单的方法可以在实体框架中编写以下SQL查询。

  select Sum(Salary), count(distinct(EmployeeID)) from empdb.employeesalary (where clause)

有一个我需要选择这些值的类

  class EmployeeEntity
  {
       decimal TotalAmount;
       int EmployeeCount 
  }

我目前在EF中执行两个查询,如下所示

  objectcontext.employeesalary.Sum(c => c.Salary);
  objectcontext.employeesalary.Select(c => c.EmployeeID).Distinct().Count();

如何使用Entity Framework将这些合并到单个语句中。我在这里错过了一些东西。

2 个答案:

答案 0 :(得分:4)

尝试这样的事情:

objectcontext.employeesalary
   .Where(c => ...)
   .GroupBy(_ => default(string))
   .Select(g => new
   {
      Sum = g.Sum(c => c.Salary),
      Count = g.Select(c => c.EmployeeID).Distinct().Count()
   });

答案 1 :(得分:2)

这是怎么回事?您可以将EF的结果合并到您的员工实体类

   var q =  from f in objectcontext.employeesalary
             where [clause]
             group f by f.EmpID into g
             select new EmployeeEntity
             {
                 TotalAmount = g.Sum(c => c.Salary),
                 EmpmloyeeCount = g.Select(c => c.EmployeeID).Discinct().Count()
             }

    var EmployeeSummary = new List<EmployeeEntity>(q.ToList());