2013-03-26 43 views
0

我只是想为一个类似的LINQ或lambda表达式以下SQL查询语句:SQL查询中的LINQ或Lambda表达式

select(sum(a.credit) - sum(a.debit)) as total 
from table_A a inner join table_B b on 
a.accountid = b.id 
where a.[date] >= '2013-01-01' 
and a.[date] < '2013-03-27' 
and b.Name = 'MKBank' 

任何帮助表示赞赏。

+0

我试图变种P = db.Account_Transaction.join(db.Accounts,O => o.AccountId,p值=> p.ID,(邻,对)=> new {o,p})。其中(o => ooDate> ='2013-01-01'&& ooDate <'2013-03-31')。GroupBy(grp => new {grp.o.debit, grp.o.credit})。select(result => new {result.sum(o => oocredit-o => oodebit)});但我得到了一个像无效的匿名声明等错误 – 2013-03-27 00:14:32

回答

0

这应该工作:

  var qr = from a in lA 
       join b in lB on a.Id equals b.Id 
       where a.Date >= new DateTime(2013, 1, 1) && 
       a.Date < new DateTime(2013, 3, 7) && 
       b.Name == "MKBank" 
       select new 
       { 
        cr = a.credit, 
        db = a.debit 
       }; 

     var res = qr.Sum((x) => x.cr - x.db); 
+0

感谢您的帮助,但我试过了,它似乎并没有给我任何结果。 – 2013-03-27 00:13:41

0

你看到这个错误是因为你是如何在声明的最后选择您的匿名类型。如果您想指定除属性名称以外的任何属性名称进行选择,则需要指定一个成员名称。阅读Anonymous Types (C# Programming Guide)了解更多详情。

您的查询还有其他一些问题。您也无法比较DateTimestring值,因此您应该在将它们传递给查询之前构造日期参数。如果您只想要一个帐户的总数,则不需要执行任何.GroupBy.Select。最后o => o.o.credit - o => o.o.debit不会编译。我认为你想要的是o => o.o.credit - o.o.debit

尝试此代替:

DateTime beginDate = ... 
DateTime endDate = ... 
p = db.Account_Transaction.Join(
     db.Accounts, 
     o => o.AccountId, 
     p => p.ID, 
     (o, p) => new { o, p }) 
    .‌Where(o => o.o.Date >= beginDate && o.o.Date < endDate && o.p.Name == "MKBank") 
    .Sum(o => o.o.credit - o.o.debit);