[英]linq query using joins and aggregate functions
I want to write a linq query which retrieves the data in the following format. 我想编写一个linq查询,该查询以以下格式检索数据。
Assume that there are two tables - Department
and Employee
假设有两个表Department
和Employee
Department
Dept_id| Manager_id
Employee
Emp_id| Dept_id| Emp_data
The relationship between Department
and Employee
table is one to many. Department
表与Employee
表之间的关系是一对多的。 The Department
table also stores the manager employee id in that particular department. “ Department
表还存储该特定部门中的经理雇员ID。 So Manager_id
is nothing but the employee_id
. 因此, Manager_id
只不过是employee_id
。
Now I want to get the data as follows 现在我想获取数据如下
Dept_id, Manager_id, Emp_data(data of Manager_id), Count(employees in that department)
If I do the join on two tables i can get data of Manager but unable to get the count of all employees in that department. 如果我在两个表上进行联接,则可以获取Manager的数据,但无法获取该部门中所有员工的人数。 Any help would be appreciated. 任何帮助,将不胜感激。
You could do something like this: 您可以执行以下操作:
var result=
(
from dep in db.Department
join emp in db.Employee
on dep.Manager_id equals emp.Emp_id
select new
{
dep.Dept_id,
emp,
NumberOfEmp= db.Employee.Count(c=>c.Dept_id==dep.Dept_id)
}
).ToList();
Where db
is the linq data context 其中db
是linq数据上下文
You could do a group join. 您可以进行群组加入。 If you have a preferred handcoded SQL statement that you would like to be generated from your LINQ query. 如果您希望从LINQ查询中生成首选的手工编码SQL语句。 You may want to experiment a bit with different formats to see which one allows you to generate the "best" SQL. 您可能需要尝试不同的格式,以查看哪种格式可以生成“最佳” SQL。
var result = from d in context.Departments
join e in context.Employees on d.dept_id equals e.dept_id into g
select new {
dept_id = d.dept_id,
manager_id = d.manager_id,
manager_data = g.Single(x => x.emp_id == d.manager_id).emp_data,
employee_count = g.Count()
};
or 要么
var result = from d in context.Departments
join e in context.Employees on d.dept_id equals e.dept_id into g
from m in g where m.emp_id == d.manager_id
select new {
dept_id = d.dept_id,
manager_id = d.manager_id,
manager_data = m.emp_data,
employee_count = g.Count()
};
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.