LINQ使用sum和group by进行子选择查询?

时间:2010-11-17 21:00:28

标签: linq group-by subquery sum

任何人都可以帮我解决LINQ查询问题。我已经转换了大部分内容,但我在存储过程中有一个子查询,我无法弄清楚如何做到这一点..

基本上这是旧的存储过程(为了方便而截断)

 SELECT  M.Period AS 'Period' ,
            C.Code AS 'Group' ,
            C.ClientCode AS 'Code' ,
            C.ClientName AS 'Name' ,
            ( SELECT    SUM(Amount) AS Expr1
              FROM      M
              WHERE     ( ClientCode = C.ClientCode )
              GROUP BY  ClientCode
            ) AS 'Amount' ,

从上面可以看出,子查询就是这样

              SELECT    SUM(Amount) AS Expr1
              FROM      M
              WHERE     ( ClientCode = C.ClientCode )
              GROUP BY  ClientCode
            ) AS 'Amount'

所以我已经完成了所有的连接,到目前为止我已经完成了这项工作。

 var test = from c in C join h in H on c.Code 
            equals h.Code join m in M on c.ClientCode   
            equals m.ClientCode 
            select new 
            { 
                Period=m.Period,
                Group=c.Code,
                Code= c.ClientCode,
                Name= c.ClientName,
                <-- Here is where i need the sub select query above -->
            };

但是我不知道如何做子查询。列的名称将是您在旧存储过程中可以看到的金额。

我希望得到任何反馈或帮助

感谢

1 个答案:

答案 0 :(得分:2)

我不确定你的SQL查询的最后一部分,但我假设这样的事情

SELECT  M.Period AS 'Period' ,
C.Code AS 'Group' ,
C.ClientCode AS 'Code' ,
C.ClientName AS 'Name' ,
( SELECT    SUM(Amount) AS Expr1
  FROM      M
  WHERE     ( ClientCode = C.ClientCode )
  GROUP BY  ClientCode
) AS 'Amount' 
from C inner join M on C.ClientCode = M.ClientCode

所以你的LINQ就是这个

var test = from c in db.C
select new {
  Period = c.M.Period,
  Group = c.Code,
  Code = c.ClientCode,
  Name = c.ClientName,
  Amount = (System.Int32)
    ((from m0 in db.M
    where
      m0.ClientCode == c.ClientCode
    group m0 by new {
      m0.ClientCode
    } into g
    select new {
      Expr1 = (System.Int32)g.Sum(p => p.Amount)
    }).First().Expr1)
}