使用LINQ / Lambda的SELECT,MAX语句的WHERE条件

时间:2019-02-26 13:39:54

标签: c# sql-server linq lambda

我正在尝试将下面的SQL查询转换为C#中的LINQ / Lambda

SELECT DISTINCT M.InternalID, P.Code
    FROM (
        dbo.MeasureValue MV
        INNER JOIN dbo.Measure M ON MV.MeasureID = M.ID
        INNER JOIN dbo.Provider P ON MV.ProviderID = P.ID
    )
    WHERE MV.ReportingDate = (
        SELECT MAX(ReportingDate)
        FROM (
            SELECT ReportingDate
            FROM dbo.MeasureValue
            WHERE MeasureID = MV.MeasureID
        )  MaxReportingDate
    );

我到目前为止,

    (from MV in MeasureValues
join M in Measures on MV.MeasureID equals M.ID
join P in Providers on MV.ProviderID equals P.ID
Where //???
select new //Distinct?? 
{  M.InternalID, P.Code} )

有人可以指导我如何在SQL查询中使用嵌套的WHERE条件,以及如何对嵌套的SELECT和DISTINCT进行MAX运算吗?

作为一个整体,LINQ / Lamda应该输出与SQL查询相同的结果。

*我是SQL和LINQ的新手

谢谢。

1 个答案:

答案 0 :(得分:1)

尝试这个:

var query = 
    from mv in MeasureValues
    join m in Measures on mv.MeasureID equals m.ID
    join p in Providers on mv.ProviderID equals p.ID
    where mv.ReportingDate == 
        (from mv2 in MeasureValues
        where mv2.MeasureID == mv.MeasureID
        orderby mv2.ReportingDate descending
        select mv2.ReportingDate
        ).FirstOrDefault()
    select new { m.InternalID, p.Code };

var distinct = 
    from q in query
    group q by new { q.InternalID, q.Code} into gr
    select new 
    { 
        InternalID = gr.First().InternalID, 
        Code = gr.First().Code 
    };

var result = distinct.ToList();

查找最大值ReportingDate的另一种方法:

var query = 
    from mv in MeasureValues
    join m in Measures on mv.MeasureID equals m.ID
    join p in Providers on mv.ProviderID equals p.ID
    where mv.ReportingDate == MeasureValues.Where(x => x.MeasureID == mv.MeasureID).Select(x => x.ReportingDate).Max()
    select new { m.InternalID, p.Code };