查询以过滤子表中基于数据的条件

时间:2018-06-19 14:24:36

标签: linq

基于下表,我想获取所有其所有员工均处于活动状态的部门名称(活动== 1)。我专门在寻找LINQ查询。

根据以下数据,仅列出部门“ Z”。

EmpId,EmpName,DepartmentId,Active
"1",    "A",        "1",    "0"
"2",    "B",        "1",    "1"
"3",    "C",        "1",    "1"
"4",    "D",        "2",    "0"
"5",    "E",        "3",    "1"
"6",    "F",        "3",    "1"


DeptId,DeptName
"1",    "X"
"2",    "Y"
"3",    "Z"

用于实现上述目的的SQL查询如下:

SELECT `DeptName` FROM `Department` d JOIN `Employee` e ON d.`DeptId` = e.`DepartmentId` WHERE `Active` = 1 AND `DepartmentId` NOT IN 
(SELECT `DepartmentId` FROM `Department` d JOIN `Employee` e ON d.`DeptId` = e.`DepartmentId` WHERE `Active` = 0) GROUP BY `DeptName`;

1 个答案:

答案 0 :(得分:1)

假设部门与员工之间存在链接:

Departments.Where(dep => dep.Employees.All(emp => (emp.Active == "1")));

否则(从员工到部门的链接)

Employees.Where(emp => (emp.Active == "1")).
          Select(emp => emp.Department).
          Distinct();