对实体进行分组和总结

时间:2012-07-17 23:54:52

标签: 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

希望有人可以指导我。

感谢。

2 个答案:

答案 0 :(得分:4)

以下应该是类似的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)
              };

答案 1 :(得分:0)

var query =
    from at in account_transactions
    where at.financialaccountid == 47
    && at.ledgervisible == 1
    group at.financialaccountid into g
    select new
    {
        financialaccountid = g.Key,
        balance = g.Sum(at => at.creditamount) - g.Sum(at => at.debitamount)
    };