LINQ to SQL使用JOIN分组MIN

时间:2010-04-19 17:19:29

标签: sql-server vb.net linq linq-to-sql

我在使用Visual Basic获取最小值的LINQ to SQL查询时遇到问题。这是SQL:

SELECT RC.AssetID, MIN(RC.RecCode) AS RecCode, JA.EngineerNote from JobAssetRecCode RC
JOIN JobAssets JA ON JA.AssetID = RC.AssetID AND JA.JobID = RC.JobID
WHERE RC.InspState = 2 AND RC.RecCode > 0
AND RC.JobID = @JobID
GROUP BY RC.AssetID, JA.EngineerNote;

我似乎在这里绕圈子进行分组等不能让它运转起来。任何帮助将不胜感激。

编辑:史蒂文,谢谢你的帮助。转换为VB:

Dim jobResult = From asset In m_dc.JobAssets _
    From recCode In asset.JobAssetRecCodes _
    Where recCode.InspState = 2 And recCode.RecCode > 0 _
    And recCode.JobID = JobID _
    Group recCode By recCode.AssetID Into g = Group _
    Select New With {g.First().JobAssets.AssetID, _
    g.First().JobAssets.EngineerNote, _
    g.Select(Function(rec) rec.RecCode).Min()}

1 个答案:

答案 0 :(得分:0)

我不得不从查询中对您的数据模型进行逆向工程,所以这有点猜测,但我认为这个查询可能会起作用。请注意,它是C#,但将其转换为VB应该非常简单:

int jobId = [some value];

var minRecCodes =
    from asset in db.JobAssets
    from recCode in asset.JobAssetRecCodes
    where recCode.InspState == 2 && recCode.RecCode > 0 &&
        recCode.JobID == jobId
    group recCode by recCode.AssetID into g
    select new
    {
        AssetID = g.Key, 
        EngineerNote = g.First().JobAsset.EngineerNote,
        g.Select(rec => rec.RecCode).Min()
    };