LINQ和加入选择

时间:2010-09-07 13:47:18

标签: c# sql linq join

我有以下SQL:

select  o.tekst as Enhet, 
        coalesce(f.Antall,0) as AntallF, 
        coalesce(f.snitt,0) as SnittF, 
        coalesce(b.antall,0) as AntallB 
        from tblhandlingsplan hp
    inner join tblorg o on hp.eierorgid = o.orgid
    left outer join (select f.handlingsplanid, count(t.tiltakid) as Antall, coalesce(avg(convert(float,t.status)),0) as Snitt from tblhandlingsplanforbedring f left outer join tblhandlingsplantiltak t on f.forbedringsid = t.forbedringsid group by f.handlingsplanid) f on hp.handlingsplanid = f.handlingsplanid
    left outer join (select b.handlingsplanid, count(b.bevaringsid) as Antall from     tblhandlingsplanbevaring b group by b.handlingsplanid) b on hp.handlingsplanid = b.handlingsplanid
where utsendingsid = 1

这正是我想要的方式......现在我正在尝试将其转换为LINQ ...

我已经走到了这一步

from h in TblHandlingsplans
join o in TblOrgs
    on h.EierOrgID equals o.OrgID
join f in TblHandlingsplanForbedrings
    on h.HandlingsplanID equals f.HandlingsplanID into f2
join b in TblHandlingsplanBevarings
    on h.HandlingsplanID equals b.HandlingsplanID into b2
where h.UtsendingsID == 1
select new {
    Enhet = o.Tekst,
    AntallF = f2.Count(),
    AntallB = b2.Count()
}

然而现在我被卡住了...我不能为我的生活找出如何从SQL解决方案中包含平均部分...任何接受者?

我正在考虑把整个事情推到一个SP中并留下它......

1 个答案:

答案 0 :(得分:0)

var query1 = from a in DB.Table1
             select new
             {
                 Id = a.Id,
                 Average = a.B.Average()
             };

var query2 = from b in DB.Table2
             join c in query1 on b.Id equals c.Id
             select c;

只是将它自由化了,所以它可能实际上不起作用,但那是你想要做的事情吗?这将导致在使用query2时创建单个SQL查询。