如何使用linq和lambda编写这个sql查询

时间:2013-08-12 16:15:03

标签: c# linq lambda

我有一个库存表和一个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完成?

2 个答案:

答案 0 :(得分: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)                       
                             });

答案 1 :(得分: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();