1

我无法将此 SQL 查询转换为有效的 linq 语句

select sum(cena), id_auta, max(servis) from dt_poruchy left outer join mt_auta on dt_poruchy.id_auta=mt_auta.id
where dt_poruchy.servis>=3 group by id_auta;

我尝试过这样的事情,但我无法处理选择语句

   var auta = from a in MtAuta.FindAll()
                   join p in DtPoruchy.FindAll() on a equals p.MtAuta into ap
                   from ap2 in ap.DefaultIfEmpty()
                   where ap2.SERVIS >= 3
                   group ap2 by ap2.ID into grouped
                   select new {

我将不胜感激任何帮助!

4

4 回答 4

2

根据提供的有限信息(某些字段来自哪些表?),这就是我想出的。

var auta = from a in MtAuta.FindAll()
           let p = a.DtPoruchys.Where(s => s.SERVIS >= 3)
           select new
           {
               Id = a.Id,
               CenaSum = p.Sum(c => c.Cena),
               Servis = p.Max(s => s.SERVIS)
           };
于 2009-07-20T15:11:11.823 回答
1

我不确定 cena 和 servis 来自哪个表,但要创建分组总和,您可以执行类似的操作。

select new { Sum = grouped.Sum( x => x.cena ) }

并获得最大值

select new { Max = grouped.Group.Max( x => x.servis ) }

这里给你一个很好的参考。

于 2009-07-20T15:08:29.473 回答
1

我已经达到了这个解决方案(假设“cena”属于MtAuta.FindAll()):

        var auta = from e in
                       (from a in DtPoruchy.FindAll()
                        where a.SERVIS >= 3
                        join p in MtAuta.FindAll() on a.MtAuta equals p.Id into ap
                        from ap2 in ap.DefaultIfEmpty()
                        select new
                        {
                            Cena = ap.cena,
                            IdAuta = a.MtAuta,
                            Servis = a.servis
                        })
                   group e by e.IdAuta into g
                   select new
                   {
                       Cena = g.Sum(e => e.cena),
                       IdAuta = g.Key,
                       Servis = g.Max(e => e.servis)
                   };
于 2009-07-20T15:17:33.747 回答
0

我稍微修改了你的解决方案,我让它像这样工作:

var auta = from jo in
                       (
                           from a in MtAuta.FindAll()
                           join p in DtPoruchy.FindAll() on a equals p.MtAuta into ap
                           from ap2 in ap.DefaultIfEmpty()
                           where ap2.SERVIS >= 3
                           select new
                           {
                               Cena = ap2.CENA,
                               Idauto = ap2.ID_AUTA,
                               Servis = ap2.SERVIS
                           }
                       )
                   group jo by jo.Idauto into g
                   select new
                   {
                       Cena = g.Sum(jo => jo.Cena),
                       IdAuto = g.Key,
                       Servis = g.Max(jo => jo.Servis)
                   };

我只是好奇这是否是最好的解决方案?

于 2009-07-20T17:35:05.623 回答