开发者

How to convert a query consisting of INNER JOIN, LEFT JOIN and GROUP BY to a similar linq2sql query?

I'm trying to convert the following T-SQL query to linq2sql one. Whatever I do, it translates it to some nasty stuff with cross joins. Any suggestion?

Given tables A, B, C

SELECT A.Id, A.Name, Pool.Total
FROM A
INNER JOIN B ON A.Id = B.AId
LEFT JOIN (
SELECT AId,
SUM(Quantity) as Total
FROM C 
GROUP BY AId) AS Pool ON A.Id = C.AId
WHERE Pool.To开发者_开发百科tal < B.Threshold


I wrote a LINQ query which indeed translates to APPLYs, but the execution plan looks the same, and the query cost in the batch is 50/50, so i would say the translated query is the same(or is a synonym).

The linq query is

from a in As 
join b in Bs on a.ID equals b.AID 
join  pool in (from c in Cs
                group c by c.AId into cG
                select new {AID = cG.Key,Total = cG.Sum(c=>c.Quantity)} ) on a.ID equals pool.AID into poolG
from pool in poolG.DefaultIfEmpty()
where pool.Total<b.Threshold 
select new {a.ID, a.Name, pool.Total}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜