[英]SQL - CASE statement in filter with optional use
Sorry I don't have better words to title my questions but essentially I am looking for an implementation of CASE/AND...OR statement in the filter condition where if the value of the particular ID is NOT NULL and greater than 0, then only the condition for that ID would be considered otherwise the condition for that ID need not be used at all. 抱歉,我没有更好的词来说明我的问题,但是本质上我正在寻找过滤条件下的CASE / AND ... OR语句的实现,如果特定ID的值不为NULL且大于0,则仅考虑该ID的条件,否则根本不需要使用该ID的条件。
Example 1: 范例1:
select emp_id, cust_id, date_id
from employee a
join customer l
on a.id = l.id
join time_table ACT
on a.join_date_id = ACT.date_id
where a.emp_id = 1
and l.cust_id in (2, 3)
and ACT.date_id >= to_char((sysdate - EXTRACT(DAY FROM (SYSDATE))) - 90, 'DD-MON-YYYY')
and ACT.date_id <= to_char(sysdate - EXTRACT(DAY FROM (SYSDATE)), 'DD-MON-YYYY')
and a.sub_emp_id = CASE WHEN @sub_emp_id IS NOT NULL AND @sub_emp_id > 0 THEN @sub_emp_id WHEN @sub_emp_id IS NULL THEN @sub_emp_id ELSE @sub_emp_id END -- where condition is, if sub_emp_id is not null and if sub_emp_id > 0 then use the value of sub_emp_id otherwise if sub_emp_id is NULL, then don't use the condition for sub_emp_id altogether.
Example 2 - 示例2-
select emp_id, cust_id, date_id
from employee a
join customer l
on a.id = l.id
join time_table ACT
on a.join_date_id = ACT.date_id
where (a.emp_id = 1
and l.cust_id in (2, 3)
and ACT.date_id >= to_char((sysdate - EXTRACT(DAY FROM (SYSDATE))) - 90, 'DD-MON-YYYY')
and ACT.date_id <= to_char(sysdate - EXTRACT(DAY FROM (SYSDATE)), 'DD-MON-YYYY')
and a.sub_emp_id > 0)
OR
(a.emp_id = 1
and l.cust_id in (2, 3)
and ACT.date_id >= to_char((sysdate - EXTRACT(DAY FROM (SYSDATE))) - 90, 'DD-MON-YYYY')
and ACT.date_id <= to_char(sysdate - EXTRACT(DAY FROM (SYSDATE)), 'DD-MON-YYYY')) -- where condition is, "if sub_emp_id is not null and if sub_emp_id > 0" then use the value of sub_emp_id otherwise "if sub_emp_id is NULL, then don't use the condition for sub_emp_id altogether".
If I understand you correctly, you'll want your filter on sub_emp_id
to look like this: 如果我对您的理解正确,那么您将希望对sub_emp_id
的过滤器如下所示:
...
and (@sub_emp_id is null or
@sub_emp_id <= 0 or
a.sub_temp_id = @sub_emp_id)
Often you need to to have null match to "all". 通常,您需要将空匹配到“所有”。 The easy pattern for that is this: 一个简单的模式是这样的:
WHERE coalesce(@sub_emp_id, a.sub_temp_id) = a.sub_temp_id
I think you were shooting for this: 我认为您正在为此拍摄:
case
when @sub_emp_id > 0 /* not null is also implied */
then case when a.sub_emp_id = @sub_emp_id then 1 else 0 end
else 1
end = 1
And I think these are equivalent alternatives: 我认为这些是等效的替代方法:
not (@sub_emp_id > 0 and a.sub_emp_id <> @sub_emp_id)
coalesce(@sub_emp_id, 0) <= 0 or a.sub_emp_id = @sub_emp_id
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.