LINQ with SUM()JOIN

时间:2012-05-13 02:56:57

标签: c# linq sql-to-linq-conversion

我正在尝试将这个SQL语句翻译成LINQ,但我在LINQ中是非常新的

select professor.nom, professor.llinatge,
SUM(case when falta.aprovada = 1 then 1 else 0 end) as FJ,
SUM(case when falta.aprovada = 0 then 1 else 0 end) as FNJ
from falta inner join professor on falta.id_profe = professor.id_profe
group by professor.llinatge, professor.nom

我无法在LINQ中使用JOIN来完成这项工作。我在LINQ中对此的最好理解是:

var query = from f in db.falta
join p in db.professor
on f.id_profe equals p.id_profe
group f by new {p.nom, p.llinatge, f.aprovada} into g
select new 
{
    nombre = g.Key.nom + " "+ g.Key.llinatge,
    fj = g.Select(s=> s.aprovada == true).Count(),
    fnj = g.Select(s=> s.aprovada == false).Count()
 };

谢谢!

2 个答案:

答案 0 :(得分:1)

您可以尝试SQL to LINQ ...多年来我一直认为Linq Pad是一个非常方便的工具......

答案 1 :(得分:0)

最后,我找到了与我的SQL语句匹配的LINQ查询:

from falta in db.Falta
join professor in db.Professor on falta.Id_profe equals professor.Id_profe
group new {professor, falta} by new {
  professor.Llinatge,
  professor.Nom
} into g
select new {
  g.Key.Nom,
  g.Key.Llinatge,
  FJ = (System.Int64?)g.Sum(p => (
  p.falta.Aprovada == true ? 1 : 0)),
  FNJ = (System.Int64?)g.Sum(p => (
  p.falta.Aprovada == false ? 1 : 0))
};

感谢您的帮助!希望这有帮助!