我想在linq
到sql
中进行此查询。
请帮忙。我是linq
的新用户,对group by clause
感到有疑问。
以下是sql query
select count(USERID), d.DEPTNAME from USERS u
join department d on u.DEPTID = d.DEPTID
group by u.DEPTID, d.DEPTNAME
答案 0 :(得分:1)
更直接的翻译是这样的:
var query =
from u in db.Users
join d in db.Departments on u.DeptId equals d.DeptId
group d by new { d.DeptId, d.DeptName } into g
select new
{
g.Key.DeptName,
Count = g.Count(),
};
虽然我认为最好这样写:
// looks like we're counting users in each department
var query =
from d in db.Departments
select new
{
d.DeptName,
Count = db.Users.Count(u => u.DeptId == d.DeptId),
};