WHERE (ADDR1 = '1500 Valley Rd' AND CUST_FLAG = 'P') -- 1
OR (ADDR1 = '1500 Valley Rd' AND CUST_FLAG = 'J') -- 2
请帮我解决这条问题。我只需要显示CUST_FLAG = 'P'
的记录。使用上面的Where子句,如果两个条件都满足,我将获得两个记录。
我的要求是:
CUST_FLAG = 'P'
CUST_FLAG = 'J'
CUST_FLAG = 'P'
的记录。答案 0 :(得分:1)
这是优先级查询。要在单个where
子句中执行此操作,您可以执行以下操作:
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'
))
或者更典型的方法是使用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;
答案 1 :(得分:0)
尝试玩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
答案 2 :(得分:0)
您可以通过对记录进行排序并仅获取第一个记录来实现此目的。 (但请注意,ROWNUM可能是特定于Oracle的语法。)
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
自Oracle 12c以来,还可以使用以下语法:
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;
另见: - On ROWNUM and Limiting Results - How do I limit the number of rows returned by an Oracle query after ordering?