使用linq从不同的表中选择sum列

时间:2011-03-31 14:35:59

标签: linq group-by sum

这是我的linq代码..

( from Order o in masterRepository.Orders.Where(x => x.IsDeleted == false)
                join OrderItem oi in masterRepository.OrderItems on o.OrderID equals oi.OrderID
                group oi by new {o.StoreID, o.CreatedOn.Year, o.CreatedOn.Month, StoreNmae="Test" } into g
                        select new ST_SalesOrder
                       {
                         Year = g.Key.Year,
                         Month = g.Key.Month,
                         StoreID = g.Key.StoreID,
                         StoreName = "SA",
                         SubTotal = g.Sum(o => o.SubTotal),
                         Shipping = g.Sum(o => o.ShippingPrice),
                         Tax = g.Sum(o => o.Tax),
                         TotalAmount = g.Sum(o => o.Total),
                         TotalCount = g.Sum(oi => oi.Quantity)
                         }).OrderBy("Year desc, Month desc, StoreName").ToList();

事情就是...... 我需要从Order表和OrderItem表中获取sum数据。 但我只能用一张桌子分组。

如果我将o分组......然后TotalCount = g.Sum(oi => oi.Quantity)< - 这会导致错误, 如果我将oi分组...然后SubTotal = g.Sum(o => o.SubTotal), Shipping = g.Sum(o => o.ShippingPrice), Tax = g.Sum(o => o.Tax),< - 这些会导致错误......

我该怎么办!!! 请帮忙。

1 个答案:

答案 0 :(得分:1)

你可以

group new { Item = oi, Order = o } by new {o.StoreID, o.CreatedOn.Year, o.CreatedOn.Month, StoreNmae="Test" } into g

然后你可以求和

g.Sum(o => o.Order.Total)

g.Sum(o => o.Item.Quantity)