-1

我有一个库存表和一个 stocktransactions 表。库存中的物品可以出售或免费分发。我想编写一个查询,检索每件商品的总销售量、免费分发的总量以及销售交易产生的收入。

类似于:

select i.Id,i.Title,
Sum(case when transactiontype=1 then s.MovedQuantity else 0 end) sold,

Sum(case when transactiontype=1 then s.MovedQuantity*s.UnitPrice else 0 end) Revenue,

Sum(case when transactiontype=0 then s.MovedQuantity else 0 end) distributed

From Inventory i,StockTransactions s

where i.Id=s.ItemId

group by i.Id,i.Title

linq/lambda 如何做到这一点?

4

2 回答 2

0

这可能是您需要的:

var result = Inventory.Join(StockTransactions, x=>x.Id, x=>x.ItemId,(x,y)=>new {x,y})
                      .GroupBy(a=>new {a.x.Id, a.x.Title})
                      .SelectMany(a=>
                         new {
                                a.Key.Id,
                                a.Key.Title,
                                sold = a.Sum(b=> b.y.transactiontype == 1 ? b.y.MovedQuantity : 0),
                                Revenue = a.Sum(b=>b.y.transactiontype == 1 ? b.y.MovedQuantity * b.y.UnitPrice : 0),
                                distributed = a.Sum(b=> b.y.transactiontype == 0 ? b.y.MovedQuantity : 0)                       
                             });
于 2013-08-12T16:45:26.607 回答
0

尝试这个

 var result = ((from inv in inventry.AsQueryable()
                      join st in stockTransactions.AsQueryable()
                      on inv.Id equals st.Id
                      select new { ID = inv.Id, Title = inv.Title, MovedQuantity = st.MovedQuantity, UnitPrice = st.UnitPrice })
                      .GroupBy(s=>new {s.ID,s.Title})
                      .Select(res=>new {Id=res.Key.ID,Title=res.Key.Title,Sold=transactiontype==1?res.Sum(s=>s.MovedQuantity):0,
                      Revenue=transactiontype==1?res.Sum(s=>s.MovedQuantity*s.UnitPrice):0,
                      Distributed=transactiontype==1?res.Sum(s=>s.MovedQuantity):0})).ToList();
于 2013-08-12T16:52:16.973 回答