需要Linq转换以下SQL查询

时间:2009-10-22 13:08:05

标签: sql linq group-by subquery max

select  colId,
        colTaskType,
        MaxID
from    tblTaskType
join    (
         select tblCheckList.colTaskTypeID,
                max(colItemNumber) MaxID
         from   tblCheckList
         group by colTaskTypeID
        ) x on coltaskTypeID = tblTaskType.colID

1 个答案:

答案 0 :(得分:0)

假设您正在使用linq-to-sql并在datacontext中使用这两个表。

或多或少准确的翻译将是:

var maxChecks = from checks in DataContext.tblChecklist
                group checks by checks.colTaskTypeID into g
                select new { colTaskTypeID, max = g.Group.Max(x => x.colItemNumber) };

var result = from t in DataContext.tblTaskType
             join c in maxChecks on t.colTaskTypeID equals c.colTaskTypeID
             select new { t.colId, t.colTaskTypeID, c.max };

但你可以试试:

var result = from t in DataContext.tblTaskType
             select new {
                     t.colId,
                     t.colTaskTypeID,
                     Max = (from c in DataContext.tblChecklist
                            where c.colTaskTypeID == t.colTaskTypeID
                            select c.colItemNumber).Max() };