SQL查询到LINQ左外连接

时间:2017-02-23 12:33:58

标签: c# sql sql-server linq linq-to-sql

我需要帮助将SQL查询转换为LINQ。我试过Linqer,但没有给出预期的结果。这是我的SQL查询:

SELECT
    dr.startDate,
    dr.endDate,             
    SUM(CASE WHEN me.Size <= 10 THEN 1 ELSE 0 END) AS FirstGroup,
    SUM(CASE WHEN me.Size > 10 AND me.Size <= 20 THEN 1 ELSE 0 END) AS SecondGroup,
    SUM(CASE WHEN me.Size > 20 AND me.Size <= 30 THEN 1 ELSE 0 END) AS ThirdGroup,
    SUM(CASE WHEN me.Size > 30 THEN 1 ELSE 0 END) AS FourthGroup,
    MAX(ISNULL(me.Size,0)) AS MaxSize,
    SUM(ISNULL(me.Size,0)) AS SpaceTotal
FROM
    time_intervals dr
LEFT OUTER JOIN Rooms me
ON ( me.DateTime BETWEEN dr.startDate AND dr.endDate)
GROUP BY
    dr.startDate,
    dr.endDate
ORDER BY dr.startDate

我试过的LINQ是:

  var stats = from t in time_intervals
       from q in query
       where q.DateTime >= t.startDate && q.DateTime <= t.endDate
select new { Date = t.startDate, First = (q.Size <= 10), Second = (q.Size > 10 && q.Size <= 20), Third = (q.Size > 20 && q.Size <= 30), Fourth = (q.Size > 30) };

但是这没有给出与SQL查询相同的结果。

1 个答案:

答案 0 :(得分:0)

在按开始日期和结束日期对记录进行分组时,您没有在LINQ中使用group关键字。 试试这个代码: -

            var stats = (from t in time_intervals
                        from q in query.Where(m=> m.DateTime >= t.startDate && m.DateTime <= t.endDate).DefaultIfEmpty()
                        group q by new { t.startDate, t.endDate, q.Size } into g
                        select new
                        {
                            Date = g.Key.startDate,
                            First = g.Count(m=>m.Size <= 10)
                        }).OrderBy(m => m.startDate);