简体   繁体   中英

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

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.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM