在LINQ中LEFT JOIN三个表和SUM

时间:2017-07-03 18:51:44

标签: linq sum left-join

我有三张桌子:

  • 购买的产品(RecordEntered as A)
  • 在该国销售的产品(SoldInCountry为B)
  • 在国外销售的产品(SoldOutCountry为C)

enter image description here

A中的每条记录都可以是:

  • 已进入且尚未售出
  • 仅在国内进入和销售
  • 仅在国外进入和出售
  • 在该国及国外进出售

我开始将表B中的部分分组,如下所示:

SELECT        
A.IdRecord, A.Qty, sum(isnull(B.Qty,0)) AS Expr1
FROM            
RecordEntered AS A 
LEFT OUTER JOIN
SoldInCountry AS B ON A.IdRecord = B.IdRecord
group by A.IdRecord, A.Qty

但我不知道该怎么做。

我想查询一下,向我展示我还有​​多少件库存。 像这样:

A.Qty - (SUM(ISNULL(B.Qty, 0)) + SUM(ISNULL(C.Qty, 0)))

我在SQL中编写了一个示例,但目标是LINQ:

from a in _ctx.....
  where .....
  select...

感谢

1 个答案:

答案 0 :(得分:1)

在LINQ中进行完全外部联接并不容易(请参阅我的答案:https://stackoverflow.com/a/43669055/2557128)但你不需要这样做来解决这个问题:

var numInStock = from item in RecordEntered
             select new {
                 item.Code,
                 Qty = item.Qty - (from sic in SoldInCountry where sic.IdRecord == item.IdRecord select sic.Qty).SingleOrDefault() -
             (from soc in SoldOutCountry where soc.IdRecord == item.IdRecord select soc.Qty).SingleOrDefault()
             };

我假设某个项目的每种类型只会有一个已售出的记录,如果可能有多个,则需要Sum匹配的记录:

var numInStock = from item in RecordEntered
             select new {
                 item.Code,
                 Qty = item.Qty - (from sic in SoldInCountry where sic.IdRecord == item.IdRecord select sic.Qty).DefaultIfEmpty().Sum() -
             (from soc in SoldOutCountry where soc.IdRecord == item.IdRecord select soc.Qty).DefaultIfEmpty().Sum()
             };