基于列值获取行

mv1qrgav  于 2021-08-09  发布在  Java
关注(0)|答案(1)|浏览(215)
CREATE TABLE employee(emp_no NUMBER,
                      emp_id VARCHAR2(50),
                      emp_type NUMBER)

INSERT INTO employee(emp_no, emp_id, emp_type) VALUES (1, 'John', 100);   
INSERT INTO employee(emp_no, emp_id, emp_type) VALUES (2, 'Sam', 200);

我需要为emp\u type为100的employee表写一个查询,在上面的数据上我会得到一行,但是如果emp\u type对于任何雇员都不是100,like:-

INSERT INTO employee(emp_no, emp_id, emp_type) VALUES (1, 'John', 200);   
INSERT INTO employee(emp_no, emp_id, emp_type) VALUES (2, 'Sam', 200);

那我需要所有的排。
寻找简单的查询来实现这一点。提前谢谢

fnx2tebb

fnx2tebb1#

如果你不关心性能,你可以这样做(没有测试,因为我只是想展示一下总体思路):

select * from employee where emp_type = 100
union all
select * from employee
     where not exists (select * from employee where emp_type = 100)
;

如果性能很重要,我相信以下解决方案可能会更好:

select emp_no, emp_id, emp_type
from   ( select e.*, count(case when emp_type = 100 then 1 end) over () as ct
         from   employee e
       )
where  emp_type = 100 or ct = 0
;

相关问题