我创建了一个查询块,例如:
select employee_number, name,payroll_name,effective_date,action type
from abc papf,
action ppa
where papf.person_id = ppa.person_id
现在,我必须找到具有action_type ='Q'或在表操作中没有任何值的员工。 为此,我使用了以下查询:
select * from
( select employee_number, name,payroll_name,effective_date,action type
from abc papf,
action ppa
where papf.person_id = ppa.person_id
and action_type = 'Q'
AND To_char(Nvl(ppa.effective_date, '2019-09-01'), 'YYYY-MM-DD') BETWEEN
('2019-09-01' ) AND ( '2019-12-01' )
UNION
select employee_number, name,payroll_name,effective_date,action type
from abc papf,
action ppa
where papf.person_id = ppa.person_id
and action_type IS NULL)
上面的查询给了我输出:
PERSON_NUMBER NAME PAYROLL_NAME EFFECTIVE_DATE ACTION_TYPE
101755 AMIH Bi weekly 2019-10-10 Q
101755 AMIH Bi weekly 2019-10-09 Q
101755 AMIH Bi weekly
1010 SAM Weekly
我想在查询的action_type = NULL部分中添加条件,以便仅返回具有空action_type的雇员,而不返回已处理的雇员,即action_type ='Q' 即员工-应该返回1010而不是没有action_type的第三行101755,因为它已经有2行具有相应的action_type,effective_Date值
答案 0 :(得分:1)
您不需要使用UNION,只需一个查询和子查询即可。
select employee_number
, name
, payroll_name
, effective_date
, action_type
from (
select employee_number
, name
, (select count(name) from abc where name = papf.name) mada
, payroll_name
, effective_date
, action_type
from abc papf
, action ppa
where papf.person_id = ppa.person_id
and (action_type = 'Q'
and nvl(ppa.effective_date, to_date('2019-09-01', 'YYYY-MM-DD')) BETWEEN
to_date('2019-09-01', 'YYYY-MM-DD') AND to_date('2019-12-01', 'YYYY-MM-DD') or action_type is null)
) where mada = 1 or action_type is not null;
这里是DEMO 希望这会对您有所帮助!
答案 1 :(得分:0)
我必须找到具有action_type ='Q'或在表操作中没有任何值的员工。
为此,您先从LEFT JOIN
开始,然后进行过滤:
select employee_number, name, payroll_name, effective_date, actiontype
from abc papf left join
action ppa
on papf.person_id = ppa.person_id
where ppa.actiontype = 'Q' or ppa.actiontype is null;
以上假设actiontype
中的NULL
不是ppa
。也许更正式的版本是:
select employee_number, name, payroll_name, effective_date, actiontype
from abc papf left join
action ppa
on papf.person_id = ppa.person_id
where ppa.actiontype = 'Q' or ppa.person_id is null;
这将检查是否确实没有匹配项。
答案 2 :(得分:0)
您可以尝试使用分析功能而不使用并集的以下查询:
Select employee_number, name,payroll_name,effective_date,action type from
(select employee_number, name,payroll_name,effective_date,action type,
row_number() over (partition by employee_number order by action_type desc nulls last) as rn
from abc papf,
action ppa
where papf.person_id = ppa.person_id
and (action_type = 'Q'
AND To_char(Nvl(ppa.effective_date, '2019-09-01'), 'YYYY-MM-DD') BETWEEN
('2019-09-01' ) AND ( '2019-12-01' ) ) or action_type is null)
Where rn = 1
干杯!