Ashkan Hovold
Ashkan Hovold

Reputation: 908

How do I write this SQL query using Linq/Lambda?

I've up until now only written simple queries using lambda like (c => c.UserID == uID) and etc., But now I have a more advanced SQL query. I wish to run against the model I've created using Entity Framework.

Problem is i cant figure out how to use group by on multiple columns and also do a distinct count on the column ObjectGUID. This is the SQL Query that works fine when I run it in SQL Server management studio.

SELECT YEAR(logdate) as year, MONTH(logdate) as month, COUNT(distinct ObjectGUID) as ammount
FROM table
WHERE ExportTemplate = 'template' AND LogDate >= '2008-01-01 00:00:00:000'
GROUP BY YEAR(logdate), MONTH(logdate)
Order By YEAR(logdate), MONTH(logdate)

Is it better to combine this with linq or could it all be done by lambda expressions? Any help would be appreciated

Upvotes: 0

Views: 205

Answers (1)

Jarek
Jarek

Reputation: 3379

You need to create new anonymous type for groupping;

from x in Model
group by new { x.Date.Year, x.Date.Month } into g
order by g.Key.Year, g.Key.Month
select new
{
    g.Key.Year,
    g.Key.Month,
    Count = g.Select(s => s.ObjectGUID).Distinct().Count()
}

Something like this should do the trick (not tested though). Adding where conditions should be easy.

Upvotes: 2

Related Questions