Linq to SQL with Left Outer Join and Group by With Sum - How to

时间:2009-11-06 13:32:28

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

我正在尝试将下面的SQL查询转换为Linq to SQL

select Categorias.IdCategoria, Categorias.Nome, SUM(lancamentos.valor)
from   lancamentos
left outer join Categorias on Lancamentos.IdCategoria = Categorias.IdCategoria
where  Month(DataLancamento) = 11
and    Credito = 1
and    Lancamentos.Ocultar = 0
group by Categorias.IdCategoria, Categorias.Nome

这就是我所做的

from    lancamento in Lancamentos
where   lancamento.Credito == true
&&      lancamento.Ocultar == false
&&      lancamento.DataLancamento.Month == 10
join    categoria in Categorias on lancamento.IdCategoria equals categoria.IdCategoria into temp
from    lancamentoJoinCategoria in temp.DefaultIfEmpty()
group   lancamentoJoinCategoria by new { lancamentoJoinCategoria.IdCategoria, lancamentoJoinCategoria.Nome } into x
select  new {
        IdCategoria = (int?)x.Key.IdCategoria
        , Nome = x.Key.Nome
}

如何将SUM(lancamentos.valor)添加到linq to sql上面?

3 个答案:

答案 0 :(得分:0)

它将是:

(from lancamento in Lancamentos
join categoria in Categorias on lancamento.IdCategoria equals categoria.IdCategoria into temp
from lancamentoJoinCategoria in temp.DefaultIfEmpty()

where lancamento.Credito == true
&& lancamento.Ocultar == false
&& lancamento.DataLancamento.Month == 10

group lancamento by new { lancamentoJoinCategoria.IdCategoria, lancamentoJoinCategoria.Nome } into x
select new
{
    IdCategoria = (int?)x.Key.IdCategoria,
    Nome = x.Key.Nome,
    sumValor = x.Sum(a=>a.valor)
});

答案 1 :(得分:-1)

您使用.Sum()方法。

EG;

Public Sub LinqToSqlCount03()
    Dim q = (From o In db.Orders _
        Select o.Freight).Sum()

Console.WriteLine(q)
End Sub

答案 2 :(得分:-1)

根据MSDN,没有与Sum()操作等效的查询表达式。 我提供了一些示例,您可以在查询中使用Sum()的方法语法。

  

一些查询操作,例如Count   或Max,没有等效的查询   表达条款,因此必须   表示为方法调用。方法   语法可以与查询结合使用   语法有多种方式。更多   信息,请参阅LINQ Query Syntax versus Method Syntax (C#)

var example = new[]
    {
        new { Count = 1, Name = "a" }, new { Count = 2, Name = "b" },
        new { Count = 2, Name = "c" }, new { Count = 2, Name = "c" }
    };

var result = from x in example
                select new 
                {
                    x.Name, 
                    Sum = (from y in example 
                           where y.Count.Equals(2) 
                               && y.Name==x.Name
                           select y.Count).Sum()
                };
var distinct = result.Distinct().ToList();