2017-04-21 231 views
0

在這裏掙扎學習linq。我試圖得到每個員工的總銷售額。我有它在SQL但不知道是否有人在LINQ甚至有可能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() 

這仍然總計爲一切不能總銷量爲員工

回答

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 };