使用sum with group by将Sql Query转换为linq

时间:2014-11-13 10:39:39

标签: c# sql-server linq linq-to-sql linq-to-entities

我是linq的新手可以帮助我将以下查询转换为linq。

   SELECT A.Name,
   Sum(C.MoneyIN) - Sum(C.MoneyOut) AS Balance
   FROM   Customers A
   JOIN   Banks B ON A.Id = B.id
   JOIN   BankTransactions C ON B.Id = C.BankID
   GROUP  BY A.Name

我尝试将其转换为linq

var query =  from c in db.Customers
                     join b in db.Banks on c.Id equals b.CustomerId
                     join bt in db.BankTransactions on b.Id equals bt.BankId                         
                     group c by c.Name into Cust                         
                     select new
                     {
                         Name = c.Name,
                         Balance = Cust.Sum(bt.MoneyIn) - Cust.Sum(bt.MoneyOut) 
                     };

有人可以告诉我哪里错了吗?

提前致谢。

2 个答案:

答案 0 :(得分:3)

试试:

var query =  from c in db.Customers
                     join b in db.Banks on c.Id equals b.CustomerId
                     join bt in db.BankTransactions on b.Id equals bt.BankId                         
                     group bt by c.Name into Cust                         
                     select new
                     {
                         Name = Cust.Name,
                         Balance = Cust.Sum(x => x.MoneyIn) - Cust.Sum(x => x.MoneyOut) 
                     };

似乎问题是,在上次选择时您使用了c.Name,但应该Cust.Name,因为您已经执行了分组。

更新1。

此外Cust.Sum(bt.MoneyIn) => Cust.Sum(x => x.MoneyIn)

更新2。

你也是错误的道具分组。如果您想将总和应用于您的BankTransactions,您需要将其分组,如:

  

将c.Name分组 bt 到Cust

所以工作示例可能如下:

public class Customer
        {
            public int Id { get; set; }
            public string Name { get; set; }
        }

        public class Bank
        {
            public int CustomerId { get; set; }
            public int Id { get; set; }
        }

        public class BankTransaction
        {
            public int BankId { get; set; }
            public int MoneyIn { get; set; }
            public int MoneyOut { get; set; }
        }

编译的查询:

var customers = new List<Customer>();
            var banks = new List<Bank>();
            var bankTransactions = new List<BankTransaction>();

            var result = from c in customers
                join b in banks on c.Id equals b.CustomerId
                join bt in bankTransactions on b.Id equals bt.BankId                         
                group bt by c.Name into Cust
                select new { Name = Cust.Key, Balance = Cust.Sum(x => x.MoneyIn) - Cust.Sum(x => x.MoneyIn) };

答案 1 :(得分:1)

总之,您需要使用对象的别名。请参阅Sum() here,如果MoneyInMoneyOutint则必须使用this overload

Chnage this:

Balance = Cust.Sum(bt.MoneyIn) - Cust.Sum(bt.MoneyOut) 

到此:

Balance = Cust.Sum(x=>x.bt.MoneyIn) - Cust.Sum(x=>x.bt.MoneyOut) 

Name的{​​{1}}是分组的

Cust

完整查询:

select new
      {
        Name = Cust.Key,
        Balance = Cust.Sum(x => x.bt.MoneyIn) - Cust.Sum(x => x.bt.MoneyOut) 
      };