Reputation: 13
WHERE (ADDR1 = '1500 Valley Rd' AND CUST_FLAG = 'P') -- 1
OR (ADDR1 = '1500 Valley Rd' AND CUST_FLAG = 'J') -- 2
Please help me with this piece of query. I need to show only the record with CUST_FLAG = 'P'
. With the above Where clause I am getting both the records if both the conditions are satisfied.
My Requirement is:
CUST_FLAG = 'P'
CUST_FLAG = 'J'
CUST_FLAG = 'P'
.Upvotes: 1
Views: 1566
Reputation: 169
You can achieve this by sorting the records and only taking the first one. (But note that ROWNUM might by Oracle-specific syntax.)
SELECT * FROM (
SELECT <column_list>
FROM <table>
WHERE ((ADDR1 = '1500 Valley Rd' AND CUST_FLAG = 'P') -- 1
OR (ADDR1 = '1500 Valley Rd' AND CUST_FLAG = 'J')) -- 2
ORDER BY CUST_FLAG DESC
) WHERE ROWNUM = 1
Since Oracle 12c, the following syntax is also possible:
SELECT <column_list>
FROM <table>
WHERE ((ADDR1 = '1500 Valley Rd' AND CUST_FLAG = 'P') -- 1
OR (ADDR1 = '1500 Valley Rd' AND CUST_FLAG = 'J')) -- 2
ORDER BY CUST_FLAG DESC
FETCH FIRST 1 ROWS ONLY;
See also: - On ROWNUM and Limiting Results - How do I limit the number of rows returned by an Oracle query after ordering?
Upvotes: 0
Reputation: 1269873
This is a prioritization query. To do this in a single where
clause, you can do:
WHERE ADDR1 = '1500 Valley Rd' AND
(CUST_FLAG = 'P' OR
(CUST_FLAG = 'J' AND
NOT EXISTS (SELECT 1 FROM t WHERE t.ADDR1 = outer.ADDR1 AND t.CUST_FLAG = 'J'
))
Or a more typical way is to use ROW_NUMBER()
:
select t.*
from (select t.*, row_number() over (partition by addr1 order by cust_flag desc) as seqnum
from (<your query here>) t
) t
where seqnum = 1;
Upvotes: 1
Reputation: 570
Try to play around case/when
case
when ADDR1 = '1500 Valley Rd' AND CUST_FLAG = 'P' then 'P'
when ADDR1 = '1500 Valley Rd' AND CUST_FLAG = 'J' then 'J'
else 'P' end
Upvotes: 0