sql - 对实体进行分组和求和

标签 sql linq linq-to-entities

我有以下 SQL 查询,我尝试将其转换为 LINQ,但没有成功:

select 
at.financialaccountid,
SUM(creditamount)-SUM(debitamount)
from account_transactions at
where at.financialaccountid = 47
and ledgervisible = 1
GROUP BY at.financialaccountid

Result of Query

希望有人可以指导我。

谢谢。

最佳答案

以下应该是一个类似的 C# LINQ 实现:

class AccountTransaction
{
    public int FinancialAccountId { get; set; }
    public bool LedgerVisible { get; set; }
    public decimal CreditAmount { get; set; }
    public decimal DebitAmount { get; set; }
}

var transactions = new List<AccountTransaction>();

var results = from at in transactions
              where at.FinancialAccountId == 4 && at.LedgerVisible == true
              group at by at.FinancialAccountId into g
              select new
              {
                  FinancialAccountId = g.Key,
                  Delta = g.Sum(x => x.CreditAmount) - g.Sum(x => x.DebitAmount)
              };

关于sql - 对实体进行分组和求和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11532498/

相关文章:

sql - 带 insert 语句的 where 子句

mysql - 通过外键外部引用使用过滤器汇总子查询注释

c# - 带总和的 LINQ GroupBy

.net - 忽略 LINQ to XML 中的命名空间

c# - 该类型出现在单个 LINQ to Entities 查询中的两个结构上不兼容的初始化中

关于一次打印3个表的SQL查询

sql - 嵌套sql的返回值

c# - Linq:将 memberExpression 类型转换为不可空

使用 SequenceEqual 可枚举方法的 LINQ to Entities 错误

c# - Entity Framework 查询中的多个连接