I need help with converting a SQL query to LINQ. I tried with Linqer but that didn't give the expected results. This is my SQL query:
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
The LINQ i tried is:
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) };
But that didn't give the same result as the SQL query.
You are not using group keyword in your LINQ while you are grouping records by by start date and end date. Try this code:-
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.