使用sum将sql查询转换为linq

时间:2017-06-14 16:36:56

标签: sql oracle linq

我在下面有这个sql查询,我试图在linq中编写,不知道如何处理总和,分组依据,顺序依据。任何帮助将不胜感激。

SELECT e.POL, SUM(e.EMS), f.FACID, d.DISN, f.FNAME, f.FCITY
FROM FAC f
INNER JOIN DISTRICT d on f.DIS = d.DIS
INNER JOIN EMS e on f.FACID = e.FACID
WHERE f.FACID = 12345
group by e.POL, f.FACID, d.DISN, f.FNAME, f.FCITY
order by e.POL, f.FACID, d.DISN, f.FNAME, f.FCITY

这是我到目前为止所做的:

                        var emissions = from f in db.FAC
                                        join d in db.DISTRICTs on f.DIS equals d.DIS
                                        join e in db.EMS on f.FACID equals e.FACID
                                        where f.FACID == facility.FACID
                                        select new
                                        {
                                            Pollutant = e.POL,
                                            Emissions = 
                                            FacilityId = f.FACID,
                                            DistrictName = d.DISN,
                                            FacilityName = f.FNAME,
                                            FacilityCity = f.FCITY
                                        };

2 个答案:

答案 0 :(得分:0)

确保您的导航属性已设置,然后:

var emissions = db.FAC
  .Where(x=>x.FACID==12345)
  .OrderBy(x=>x.DISTRICT.POL)
  .ThenBy(x=>x.FACID)
  .ThenBy(x=>x.DISTRICT.DISN)
  .ThenBy(x=>x.FNAME)
  .ThenBy(x=>x.FCITY)
  .Select(x=> new {
    Pollutant = x.DISTRICT.POL, 
    Emissions = x.EMSs.Sum(),
    FacilityId = x.FACID,
    DistrictName = x.DISTRICT.DISN,
    FacilityName = x.FNAME,
    FacilityCity = x.FCITY
  });

答案 1 :(得分:0)

尝试代码:

var result=( from f in db.FAC
             join d in db.DISTRICT on f.DIS equals d.DIS
             join e in EMS on F.FACID equlas e.FACID
             Where F.FACID=12345
             group new {f,d,e} by new {e.POL,f.FACID,d.DISN,f.FNAME,f.FCITY} into jj
             select new {
                         POL= jj.FirstOrDefault().e.POL,
                         SUMEMS= jj.ToList().Sum(c => c.e.EMS),
                         FACID= jj.FirstOrDefault().f.FACID,
                         DISN= jj.FirstOrDefault().d.DISN,
                         FNAME=jj.FirstOrDefault().f.FNAME,
                         FCITY=jj.FirstOrDefault().f.FCITY 
                        }).OrderBy(c=>c.POL).ThenBy(c=>c.FACID).ThenBy(c=>c.DISN)
                          .ThenBy(c=>c.FNAME).ThenBy(c=>c.FCITY).ToList();