【问题标题】:how to write this sql query using linq and lambda如何使用 linq 和 lambda 编写此 sql 查询
【发布时间】:2013-08-12 16:15:02
【问题描述】:

我有一个库存表和一个 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 实现这一点?

【问题讨论】:

  • 我知道如何在 linq 中使用 lambda。我只需要帮助将此 sql 翻译成有效的表达式
  • 您对哪一部分特别有困难? GroupBySelectSum 应该在正确的组合中发挥作用。
  • 什么是transactiontype
  • 它是一个int字段,指定交易是销售、入库还是免费复制分发交易

标签: c# linq lambda


【解决方案1】:

这可能是你需要的:

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

【讨论】:

  • 谢谢,这正是我所需要的。我只是用 Select 替换了 SelectMany 以使其工作。
【解决方案2】:

试试这个

 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-04-30
    • 1970-01-01
    • 2021-01-15
    • 2016-06-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多