具有多个Sums,Groupings和Joins的Linq查询

时间:2009-12-18 16:32:24

标签: linq-to-sql tsql

我有一个SQL查询,我需要将其转换为Linq to SQL。我成功了,直到Sums,我完全被困在那里。我知道如何做单/简单的分组和总和,但这次我迫切需要帮助。我很欣赏任何想法。

表关系是这样的:

TreeNodes - one-to-many - Dispatches (not every TreeNode has Dispatch entry)
Dispatches - one-to-many - DispatchesJobs (not every Dispatch has DispatchJob entry)
DispatchesJobs one-to-many - DispatchesJobsReceivings (not every DispatchJob has DispatchJobReceiving entry)

基本上我需要知道的是:

对于每个Dispatch: 从DispatchesJobsReceivings表中获取Dispatch的TreeNode名称及其数量,花费和返回计数。

这是我的SQL查询:

select t.TreeNodes_id, t.name
sum(djr.quantity) as quantity, sum(djr.returns) as returns, sum(djr.spent) as spent

from TreeNodes as t

inner join Dispatches as d
on t.TreeNodes_id = d.TreeNodes_id

left outer join DispatchesJobs as dj
on d.Dispatches_id = dj.Dispatches_id

left outer join DispatchesJobsReceivings as djr
on dj.DispatchesJobs_id = djr.DispatchesJobs_id

group by t.TreeNodes_id, t.name

这给出了这个结果:

TreeNodes_id name      quantity  returns  spent
------------ ------------ -------   -------  ---------- 
77        CEMENT      20     17      3
122       SAND           NULL    NULL     NULL

我来这里翻译它:

from t in db.TreeNodes

join d in db.Dispatches
on t.TreeNodes_id equals d.TreeNodes_id

join dj in db.Dispatches_Jobs
on d.Dispatches_id equals dj.Dispatches_id
into tmpDJ
from rowTmpDJ in tmpDJ.DefaultIfEmpty()

join djr in db.DispatchesJobsReceivings
on rowTmpDj.DispatchesJobs_id equals djr.DispatchesJobs_id
into tmpDjr
from rowTmpDjr in tmpDjr.DefaultIfEmpty()

select new 
{
   TreeNode_id = t.TreeNodes_id,
   name = t.name,
   quantity = rowTmpDjr.quantity,
   returns = rowTmpDjr.returns,
   spent = rowTmpDjr.spent
};

这给出了这个结果:

 TreeNodes_id name      quantity  returns  spent
 ------------ ------------ ------    -------- ----------
 77           CEMENT          1         0         1
 77           CEMENT          2         0         2
 77           CEMENT          4         4         0
 77           CEMENT          13     13        0
 122          SAND            NULL      NULL      NULL

我被困在这里。我很感激任何帮助。

1 个答案:

答案 0 :(得分:0)

查看名为Linqer的产品(我与之无关)。它将T-SQL转换为LINQ查询。神奇的工具。我必须遇到一个无法转换的查询。有一个30天的试用期。成本约为60美元。

兰迪