我想在 Oracle 中创建一个如下所示的查询
DECLARE
my_count NUMBER;
BEGIN
SELECT COUNT(table.column1) INTO my_count FROM table;
IF my_count > 2 THEN
SELECT * FROM table WHERE table.column2 = 'ABC';
ELSE
SELECT * FROM table WHERE table.column2 != 'ABC';
END IF;
END;
有同样效果的答案吗?
有这样的事吗?
with temp (cnt) as
(select count(column1) from table)
select * from table cross join temp where column2 = 'ABC' and cnt > 2
union all
select * from table cross join temp where column2 <> 'ABC' and cnt <= 2;
演示,基于 Scott 的示例模式:有 4 名职员,并且 - 由于该数字大于 2,我将获取在部门 10 工作的员工(即将执行第 3 行中的查询):
SQL> select count(*) from emp where job = 'CLERK';
COUNT(*)
----------
4
SQL> select ename from emp where deptno = 10;
ENAME
----------
CLARK
KING
MILLER
SQL> with temp (cnt) as
2 (select count(*) from emp where job = 'CLERK')
3 select ename from emp cross join temp where deptno = 10 and cnt > 2
4 union all
5 select ename from emp cross join temp where deptno <>10 and cnt <= 2;
ENAME
----------
CLARK --> right; here they are
KING
MILLER
由于只有一位总统,计数低于 2,查询将返回第 5 行的结果:
SQL> with temp (cnt) as
2 (select count(*) from emp where job = 'PRESIDENT')
3 select ename from emp cross join temp where deptno = 10 and cnt > 2
4 union all
5 select ename from emp cross join temp where deptno <>10 and cnt <= 2;
ENAME
----------
BLAKE
SCOTT
TURNER
ADAMS
JAMES
FORD
SMITH
ALLEN
WARD
JONES
MARTIN
11 rows selected.
SQL>