我想使用COUNT结果作为ORACLE上的IF CONDITION,就像oracle上的伪代码一样:
select count(d.number_people) as counted_people
from dual d
if counted_people = 1 then
dbms_output.put_line('Have just one people on this column.'
end if;
这种语法是错误的,我知道,我该如何正确使用它?
答案 0 :(得分:1)
使用SELECT ... INTO variable ...
演示:https://dbfiddle.uk/?rdbms=oracle_11.2&fiddle=610d02797857539be5fcd4afdbd7d9e6
DECLARE
cnt number;
BEGIN
select count(*) INTO cnt from dual;
IF cnt = 1 THEN
DBMS_OUTPUT.PUT_LINE('Exaclty one record');
ELSE
DBMS_OUTPUT.PUT_LINE('0 or more than 1 record');
END IF;
END;
/
答案 1 :(得分:1)
COUNT
是聚合结果。您可以计算表中的所有行,符合特定条件的所有行等。作为汇总结果,可以在SELECT
子句,HAVING
子句和{{ 1}}子句。 (您不能在ORDER BY
子句中使用它,因为WHERE
子句处理表行中的数据。您需要一个WHERE
子句来处理聚合结果。) / p>
SELECT子句/ ORDER BY子句示例
HAVING
HAVING子句示例
select
supplier_id,
case when count(*) < 20 then 'less then 20 orders'
when count(*) < 40 then 'less beteen 20 and 40 orders'
else '40 or more orders'
end as number_of_orders
from orders
where order_date >= date '2018-01-01'
group by supplier_id
order by count(*) desc;