根据列值获取行

时间:2020-05-19 12:57:42

标签: sql oracle

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);

我需要为employee表编写一个查询,其中emp_type为100,在上面的数据上我将得到一行,但是如果对于任何员工emp_type不是100, 像:-

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);

然后我需要所有行。

寻找简单的查询来实现。预先感谢

1 个答案:

答案 0 :(得分:0)

如果您不关心性能,则可以执行以下操作(未经测试,因为我只是想展示总体思路):

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
;
相关问题