LINQ with sub select query using sum and group by?
Can anyone help me with a LINQ query. I have converted most of it but i have a sub query in the stored procedure and i can't figure out how to do it..
basically this is the old stored procedure (truncated for ease)
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' ,
As you can see from above the sub query is like so
SELECT SUM(Amount) AS Expr1
FROM M
WHERE ( ClientCode = C.ClientCode )
GROUP B开发者_StackOverflowY ClientCode
) AS 'Amount'
So i have done all my joins and i have this so far and it works.
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 -->
};
But i am at a loss of how to do the subquery. The name of the column will be Amount as you are able to see in the old stored procedure.
I would appreciate any feedback or help
THanks
Im not sure on that last part of your SQL query but I am assuming something like this
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
so your LINQ will be this
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)
}
精彩评论