我想寫一個查詢 - 涵蓋一個案例: - 我想檢查 code_id (輸入變數)是否存在任何 misc 值,如果沒有,則使用 code_id 作為默認值(即 OTH)。
就像是
select MISC_FLAGS
from systemcode
where rec_type = 'C'
and code_type = 'SAN'
and CODE_ID = 'HT';
如果沒有這個值,那么它應該回傳結果:
select MISC_FLAGS
from systemcode
where rec_type = 'C'
and code_type = 'SAN'
and CODE_ID = 'OTH';
uj5u.com熱心網友回復:
你可以使用這個查詢
select MISC_FLAGS from systemcode where rec_type = 'C' and code_type = 'SAN' and CODE_ID = 'HT' or (
CODE_ID = 'OTH' and TABLE_ID not in (select TABLE_ID from systemcode where rec_type = 'C' and code_type = 'SAN' and CODE_ID = 'HT')
)
uj5u.com熱心網友回復:
這可能是一種選擇;閱讀代碼中的注釋。
當我在 SQL*Plus 中運行它時,我使用了替換變數;根據您的操作方式,它可能是一個系結變數 ( :par_code_id) ;或者,如果它是一個程序/函式,您只需使用par_code_id.
SQL> with systemcode (misc_flags, rec_type, code_type, code_id) as
2 -- sample data
3 (select 'MSC', 'C', 'SAN', 'OTH' from dual union all
4 select 'ABC', 'C', 'SAN', 'TT' from dual
5 ),
6 temp as
7 -- MX = 1 if :PAR_CODE_ID exists in SYSTEMCODE table
8 -- MX = 0 if :PAR_CODE_ID does not exist in SYSTEMCODE table
9 (select nvl(max(1), 0) mx
10 from systemcode
11 where exists (select null from systemcode
12 where code_id = '&&par_code_id'
13 )
14 )
15 select s.misc_flags
16 from systemcode s cross join temp t
17 where s.rec_type = 'C'
18 and s.code_type = 'SAN'
19 -- depending on MX value, select either row(s) that match :PAR_CODE_ID or 'OTH'
20 and s.code_id = case when t.mx = 1 then '&&par_code_id'
21 else 'OTH'
22 end;
Enter value for par_code_id: HT --> doesn't exist, so use OTH
MIS
---
MSC
SQL> undefine par_code_id
SQL> /
Enter value for par_code_id: TT --> it exists
MIS
---
ABC
uj5u.com熱心網友回復:
您可以使用條件的聚集來選擇OTH,并CODE_ID在不同的列的輸入。然后根據指定的CODE_ID.
create table systemcode ( MISC_FLAGS, rec_type, code_type, CODE_ID ) as select 'HT', 'C', 'SAN', 'HT' from dual union all select 'OTH', 'C', 'SAN', 'OTH' from dual
select decode( /*If the specified code is present*/ max(decode(code_id, 'HT', code_id)), 'HT', /*then select a value for that code*/ max(decode(code_id, 'HT', MISC_FLAGS)), /*else - select default value*/ max(decode(code_id, 'OTH', MISC_FLAGS)) ) as code_id from systemcode where code_id in ('HT', 'OTH')| CODE_ID | | :------ | | HT |
select decode( max(decode(code_id, 'AAA', code_id)), 'AAA', max(decode(code_id, 'AAA', MISC_FLAGS)), max(decode(code_id, 'OTH', MISC_FLAGS)) ) as code_id from systemcode where code_id in ('AAA', 'OTH')| CODE_ID | | :------ | | 奧特 |
db<>在這里擺弄
uj5u.com熱心網友回復:
如果每個代碼只有一行要回傳,您可以使用:
SELECT misc_flags
FROM (
SELECT misc_flags
FROM systemcode
WHERE rec_type = 'C'
AND code_type = 'SAN'
AND code_id IN ('HT', 'OTH')
ORDER BY code_id ASC
)
WHERE ROWNUM = 1;
如果可以有多行:
SELECT misc_flags
FROM (
SELECT misc_flags,
RANK() OVER (ORDER BY code_id ASC) AS rnk
FROM systemcode
WHERE rec_type = 'C'
AND code_type = 'SAN'
AND code_id IN ('HT', 'OTH')
)
WHERE rnk = 1;
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/371585.html
