将聚合SQL转换为linq等效项

时间:2016-08-20 15:58:11

标签: sql linq aggregate

这是我的SQL查询:

Select 
    Product.ProductName, 
    Sum(Credit) as TotalCredit, 
    Sum(Debit) as TotalDebit 
from 
    Acct_GL 
inner join 
    Product ON Acct_GL.AcctRef = Product.ProductCode
where 
    AccountId = @custaid 
    and CONVERT(Date, effdate, 103) <= CONVERT(Date, @todate, 103) 
    and (Reverse = 'N')
group by 
    Product.ProductName 

这是我想要转换为的linq查询:

var TotalAccountBalance = 
    (from pro in _db.Products
     join gl in _db.Acct_GL on pro.ProductCode.Trim() equals (gl.AcctRef.Trim())
     where gl.AccountID == CustId && 
           gl.EffDate <=FromDate && 
           gl.Reverse == "N"
     group pro by pro.ProductName into pd
     orderby pd.Key
     select new AccountBalanceModel()
                {
                     Total = Convert.ToDecimal(gl.Credit) - Convert.ToDecimal(gl.Debit)
                }).FirstOrDefault();

1 个答案:

答案 0 :(得分:0)

var TotalAccountBalance = 
(from pro in _db.Products
            join gl in _db.Acct_GL on pro.ProductCode equals gl.AcctRef
            where gl.AccountID == CustId && gl.EffDate <= FromDate && gl.Reverse == "N"
            group pro by pro.ProductName into pd
            select new AccountBalanceModel()
            {
                ProductName = pd.key,
                Total = (decimal)pd.Sum(x=>x.Credit) - (decimal)pd.Sum(x=>x.Debit)
            }).ToList();