我需要编写一个程序或函数来返回应满足以下条件的状态,年龄和类型的计数
select * from ABC
where ABC_id = 2001
and ABC_LEVEL_ID = 1 --status
and ABC_REQUEST_DATE < sysdate --age
and ABC_TYPE_ID = 5; --type
If ABC_ID = 2001 and ABC_LEVEL_ID = 1
THEN return COUNT(STATUS)
If ABC_ID = 2001 and ABC_REQUEST_DATE < SYSDATE
THEN return COUNT(AGE)
If ABC_ID = 2001 and ABC_TYPE_ID = 5
THEN return COUNT(TYPE)
所有三个值都应该是传递给前端应用程序的OUT参数。
答案 0 :(得分:2)
您可以在查询中使用CASE
表达式来包含这些约束,例如
select *,
case when ABC_ID = 2001 and ABC_LEVEL_ID = 1 then COUNT(STATUS) else null end as testcol1,
case when ABC_ID = 2001 and ABC_REQUEST_DATE < SYSDATE then COUNT(AGE) else null end as testcol2,
case when ABC_ID = 2001 and ABC_TYPE_ID = 5 then COUNT(TYPE) else null end as testcol3
from ABC
where ABC_id = 2001
and ABC_LEVEL_ID = 1 --status
and ABC_REQUEST_DATE < sysdate --age
and ABC_TYPE_ID = 5; --type
每条评论:修改后的查询(包括@jeffrykemps早期编辑)
select *,
case when ABC_LEVEL_ID = 1 then COUNT(STATUS) end as testcol1,
case when ABC_REQUEST_DATE < SYSDATE then COUNT(AGE) end as testcol2,
case when ABC_TYPE_ID = 5 then COUNT(TYPE) end as testcol3
from ABC
where ABC_id = 2001
and ABC_LEVEL_ID = 1 --status
and ABC_REQUEST_DATE < sysdate --age
and ABC_TYPE_ID = 5; --type
答案 1 :(得分:1)
我认为如果您的WHERE子句使用OR操作而不是AND,那将更有意义。使用CASE语句可以很容易地在查询的投影中进行计数。
由于代码属于存储过程,您需要选择某些内容。这里我假设直接赋值给OUT参数。但是,如果您的代码包含其他要求,则应填充局部变量,并在过程结束时将它们分配给OUT参数。
create or replace procedure get_counts
( p_out_status_count out pls_integer
, p_out_age_count out pls_integer
, p_out_type_count out pls_integer
as
begin
select
count (case ABC_LEVEL_ID = 1 then 1 else null end),
count (case ABC_REQUEST_DATE < SYSDATE then 1 else null end),
count (case ABC_TYPE_ID = 5 then 1 else null end)
into p_out_status_count
, p_out_age_count
, p_out_type_count
from ABC
where ABC_id = 2001
and (ABC_LEVEL_ID = 1 --status
or ABC_REQUEST_DATE < sysdate --age
or ABC_TYPE_ID = 5); -- type
end get_counts;
此外,您可能想要参数化ABC_ID。在这种情况下,程序的签名可能是:
create or replace procedure get_counts
( p_abc_id in abc.abc_id%type
, p_out_status_count out pls_integer
, p_out_age_count out pls_integer
, p_out_type_count out pls_integer
)
和WHERE子句将是
....
from ABC
where ABC_id = p_abc_id
....