【问题标题】:How to perform !(true &true) type of operation如何执行 !(true &true) 类型的操作
【发布时间】:2019-10-01 20:20:02
【问题描述】:

我有一个部门表和员工表:

部门:

deptId   deptName
0        dept1
1        dept2
2        dept3
3        dept4

员工:

deptId  name    type
0       aaa     100
0       bbb     200
0       ccc     300
1       ddd     100
1       eee     300
2       fff     200
2       ggg     300
3       hhh     300

所以每个部门都有多名员工。如何检索所有没有类型 100 和 200 的员工的部门

因此,如果我运行查询,我应该得到部门 1、2 和 3,因为唯一拥有这两种类型员工的部门是部门 0

谢谢

【问题讨论】:

    标签: sql oracle


    【解决方案1】:

    一种方法使用not exists

    select d.*
    from department d
    where not exists (select 1
                      from employee e
                      where e.deptid = d.deptid and e.type = 100
                     ) or
          not exists (select 1
                      from employee e
                      where e.deptid = d.deptid and e.type = 200
                     ) ;
    

    如果你想要求部门至少有一名员工,我可能会去聚合:

    select e.deptid
    from employee e
    group by e.deptid
    having count(distinct case when e.type in (100, 200) then e.type end) < 2;
    

    【讨论】:

    • 嗨,戈登,第一种方法。如果是 OR 则返回没有 100 或没有 200 的部门。这意味着将返回所有部门。对吗?
    • @Snake 。 . .不会。对于deptid = 0,每个NOT EXISTS 都返回FALSE,这样部门就不会被返回。
    【解决方案2】:

    有一个相关的子查询,它返回一个 deptid 的不同类型 100 和 200 的数量。

    select *
    from department d
    where (select count(distinct type)
           from employee e
           where type in (100, 200)
             and e.deptid = d.deptid
           group by deptid) < 2
    

    或者用GROUP BY 做一个LEFT JOIN

    select d.deptId, d.deptName
    from department d
    left join employee e
        on e.deptid = d.deptid
    group by d.deptId, d.deptName
    having count(case when e.type = 100 then 1 end) = 0
        or count(case when e.type = 200 then 1 end) = 0
    

    【讨论】:

      猜你喜欢
      • 2011-06-17
      • 1970-01-01
      • 2012-01-23
      • 1970-01-01
      • 1970-01-01
      • 2021-11-15
      • 1970-01-01
      • 1970-01-01
      • 2011-12-24
      相关资源
      最近更新 更多