繁体   English   中英

LINQ to EF,左联接和group by子句

[英]LINQ to EF, Left Join and group by clause

我有这个SQL:

select o.prod_id, SUM(o.[count])  as [count]
    into #otgr
    from otgr o
    where o.[date]<= @date
    group by o.prod_id

    select f.prod_id, SUM(f.[count]) as [count] 
    into #factory
    from factory f
    where f.[date]<= @date
    group by f.prod_id


    select p.name, p.id, f.[count] - ISNULL(o.[count],0)  as av_count
    from products p
    join #factory f on f.prod_id = p.id
    left join #otgr o on o.prod_id = p.id
    where f.[count] - ISNULL(o.[count],0) > 0

如何将其翻译成Linq? 我坚持下面的代码:

from otgrr in db.otgr
where otgrr.date <= date
group otgrr by otgrr.prod_id into otgrs
from fac in db.factory
where fac.date <= date
group fac by fac.prod_id into facs
from prod in db.products
join fac2 in facs on prod.id equals fac2.Key
join otg2 in otgrs.DefaultIfEmpty(new {id = 0, av_count = 0 }) on prod.id equals otg2.Key
where (fac2.SUM(a=>a.av_count) - otg2.SUM(a=>a.av_count)) > 0
select new products { id = prod.id, name = prod.name, av_count = (fac2.SUM(a=>a.av_count) - otg2.SUM(a=>a.av_count))

谢谢大家,对不起我的英语不好

您也可以检查LINQPad 当然,您可以将其拆分为多个LINQ查询(毕竟,执行是延迟的,因此它将作为一个查询全部执行,而无需使用临时表。在99%的情况下,它应该更快)。

但是在您的情况下,可以使用导航属性来更简单地编写它:

var result= from p in products
            select new {Name=p.Name, 
                        Id = p.Id, 
                        Count = p.Factories.Where(f=> f.date <= date).Sum(f=>f.Count) 
                              - p.otgrs.Where(o=> o.date <= date).Sum(o=>o.Count)
                       };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM