选择具有employeeId的所有部门是否为空且不为空?

时间:2017-03-24 05:34:46

标签: mysql sql

如何选择空值为employeeId且空值为employeeId的所有部门?

id       employeeID
 1           1
 1           null
 2           2
 3           null

结果应该是部门ID - 1

8 个答案:

答案 0 :(得分:2)

select      id
from        department
group by    id
having      count(employeeId) between 1 and count(*)-1

count(employeeId)计算非NULL employeeId

  • 如果是> 0表示我们至少有一个NOT NULL值。
  • 如果是< count(*)表示我们至少有一个NULL值。

答案 1 :(得分:1)

所以你想要部门id,其中有一些null和一些非null的employeeid?

您可以使用GROUP BY减少每个部门ID的行集。

然后使用HAVING过滤组,以使组中的条目数为非零的employeeid,以及非NULL employeeid组中的非零条目数。

SELECT id
FROM Department
GROUP BY id
HAVING COUNT(CASE WHEN employeeID IS NULL THEN 1 END) > 0 
  AND  COUNT(CASE WHEN employeeID IS NOT NULL THEN 1 END) > 0;

答案 2 :(得分:0)

试试这个:

SELECT id, employeeID from tablename GROUP BY id, employeeID;

这将GROUP BY id, employeeID并返回所有记录。

答案 3 :(得分:0)

我不关于部门表结构。

您可以尝试以下查询。

对于员工ID的非空值

      SELECT id 
        FROM tablename 
       WHERE employeeID is not null 
    GROUP BY employeeID 
   INTERSECT
      SELECT id 
       FROM tablename 
      WHERE employeeID is null 
   GROUP BY employeeID

您可以尝试此解决方案。

答案 4 :(得分:0)

只需使用EXISTS

即可
SELECT DISTINCT T.id
FROM TAB T
WHERE EXISTS (SELECT 1 FROM TAB T1 WHERE T.id = T1.id AND T1.employeeID IS NULL)
AND EXISTS  (SELECT 1 FROM TAB T1 WHERE T.id = T1.id AND T1.employeeID IS NOT NULL)

答案 5 :(得分:0)

试试这个,相交会做到这一点

select * from (
SELECT id from Department WHERE employeeID is not null
INTERSECT
SELECT id from Department WHERE employeeID is null
)x

答案 6 :(得分:0)

GROUP BY。使用HAVING返回id,其中employeeID的数量大于0,也小于该id行的总数。

select id
from department
group by id
having count(employeeID) > 0
   and count(employeeID) < count(*)

count(employeeID)计算非空行。count(*)计算所有行。)

答案 7 :(得分:0)

你可以试试这个:

select id, employeeId from department order by id;