Query to filter records based on specific conditions
There is a_status_check table with the following data:
Requirement: if LC and BE status are present, then consider only LC. Otherwise, consider BE. Ignore other codes for this ID.
So, the result should look like this:
I tried the DECODE and CASE functions with no luck. Can someone help.
source to share
Use analytic functions:
select distinct
id,
first_value (status) over (partition by id order by status desc) status,
first_value (amt ) over (partition by id order by status desc) amt
from
tq84_a_status_check
where
status in ('LC', 'BE')
order by
id;
Testdata:
create table tq84_a_status_check (
id number,
status varchar2(10),
amt number
);
select distinct
id,
first_value (status) over (partition by id order by status desc) status,
first_value (amt ) over (partition by id order by status desc) amt
from
tq84_a_status_check
where
status in ('LC', 'BE')
order by
id;
source to share
This solution should work if you only have two values STATUS
(A and B). First I get a temporary table containing the count STATUS
for each ID
and then I JOIN
back to a_status_check
. The proposal WHERE
saves the entries A
when they appear separately and saves the entries B
when A
and are B
displayed together.
SELECT * FROM a_status_check t1
INNER JOIN
(
SELECT ID, COUNT(*) AS status_count
FROM a_status_check
GROUP BY ID
) t2
ON t1.ID = t2.ID
WHERE (t1.STATUS = 'A' AND t2.status_count = 1)
OR (t1.STATUS = 'B' AND t2.status_count = 2);
source to share