无法在select语句上使用连接时将SQL转换为LINQ

时间:2016-12-02 13:24:23

标签: c# sql-server linq join

民间,

尝试将以下SQL-Server命令转换为LINQ。我已经通过SSMS验证了SQL的正确运行。

select top 100 tts.* from tblLCState tts
INNER JOIN
    (SELECT fldLCID, MAX(fldStateDate) AS Statedate
    FROM tblLCState
    GROUP BY fldLCID) grptts 
ON tts.fldLCID = grptts.fldLCID 
AND tts.fldStateDate = grptts.Statedate
where fldLCStateCode = 1
order by fldStateDate desc

我很困惑如何将表tblLCState加入select语句。我对LNIQ的尝试如下:

from tRow in tblLCState
join irow2 in (from iRow in tblLCState
    group iRow by iRow.fldLCID into g
    select new {fldLCID = g.Key, MaxStateDate =  (from t2 in g select t2.fldStateDate).Max()} ) 
on ((tRow.fldStateDate = irow2.MaxStateDate) and (tRow.fldLCID = irow2.g.fldLCID))

错误发生在on子句中的and运算符上,表示a)是预期的。此时我没有尝试过where / order / top 100。只是花了很多时间在这张表格或其他任何表格上找不到运气。我看到很多帖子要加入另一张桌子,但不幸的是我没有这种奢侈品。

任何帮助都将不胜感激。

由于

汤姆D.

1 个答案:

答案 0 :(得分:1)

LINQ

  var result = (from tRow in tblLCState
                join irow2 in (from iRow in tblLCState
                                group iRow by iRow.fldLCID into g
                                select new { fldLCID = g.Key, MaxStateDate = g.Max(k => k.fldStateDate) })
                on new { StateDate = tRow.fldStateDate, tRow.fldLCID } equals new { StateDate = irow2.MaxStateDate, irow2.fldLCID }
                select tRow);