Как то так?
1-й лист -
;with test_data(order_id, order_number, reason_code) as (
select 123, 'a', 'r2' union all
select 123, 'b', 'r1' union all
select 123, 'c', 'r3' union all
select 124, 'd', 'r3'
)
--
-- Test data above; Desired query below
--
select *
from test_data a
where exists (
select 1 from test_data b
where a.order_id = b.order_id
and b.reason_code = 'r2'
)
Выход:
123 a r2
123 b r1
123 c r3
2-й лист -
;with test_data(order_id, order_number, reason_code) as (
select 123, 'a', 'r2' union all
select 123, 'b', 'r1' union all
select 123, 'c', 'r3' union all
select 124, 'd', 'r3'
)
--
-- Test data above; Desired query below
--
select *
from test_data a
where NOT exists (
select 1 from test_data b
where a.order_id = b.order_id
and b.reason_code = 'r2'
)
Выход:
124 d r3
Надеюсь, это поможет. Пожалуйста, вернитесь.