Linq嵌套查询总和

时间:2017-04-21 00:03:02

标签: c# sql-server linq

在这里苦苦挣扎学习linq。我试图得到每位员工的总销售额。我在sql中有它,但想知道它是否甚至可能在linq

的Sql

select 
  sum(t.total) as totalSales,
  e.EmployeeID,
  e.FirstName
from(
    select 
        o.OrderID,
        o.EmployeeID,
        sum(d.unitprice)total
    from Orders o
        inner join [Order Details]d
            on o.OrderID = d.OrderID        
    group by
        o.OrderID,
o.EmployeeID
)t
inner join Employees e
    on e.EmployeeID = t.EmployeeID
group by e.EmployeeID, e.FirstName
order by totalSales

的LINQ:

from a in orders
join b in orderDetails on a.OrderID equals b.OrderID
join c in employees on a.EmployeeID equals c.EmployeeID
--I had a where a.EmployeeId == c.EmployeeId
select b.UnitPrice).Sum()

这仍然是一切,而不是员工的总销售额

1 个答案:

答案 0 :(得分:0)

我从外部选择中不需要的子选择中取出了一些字段,然后得到:

from e in Employees
join t in (
    from o in Orders
    join d in Order_Details on o.OrderID equals d.OrderID
    group d by new { o.OrderID, o.EmployeeID } into dg
    let total = dg.Sum(x => x.unitprice)
    select new { dg.Key.EmployeeID, total })
  on e.EmployeeID equals t.EmployeeID
group t.total by new { e.EmployeeID, e.FirstName } into tg
let totalSales = tg.Sum()
orderby totalSales
select new { tg.Key.EmployeeID, tg.Key.FirstName, totalSales };