簡體   English   中英

如何在Oracle SQL中創建條件where子句

[英]How can I create a conditional where clause in oracle sql

表A拉回表B中的行。如果表B的col2為“ XYZ”,那么我只希望該ID包含XYZ的行。

Table A   Table B
id bid    bid  col2  
1  2      2    ABC
1  3      3    ABC
2  4      4    ABC
2  5      5    XYZ  

輸出應該總共有3行,id為1的兩行和id 2的第一行。

這是我到目前為止嘗試過的

select * from table a, table b
where a.col1 = b.col1
and if 'ABC' in (select b1.col2 from table b1 where b1.col1 = b.col1)  then b.col2 = 'ABC' end
and if 'XYZ' in (select b1.col2 from table b1 where b1.col1 = b.col1)  then b.col2 = 'XYZ' end 

我也嘗試過

and case when (select count(b1.col) from table b1 where b1.col = b.col1 and b1.col = 'XYZ') >0 then b.col1 = 'XYZ' end 

確切的代碼

select *
from scores a, queues b 
where res_id = '112321'
and b.que_id = a.que_id
and case when (select count(qasgn_cd) from queues where que_id = b.que_id and QASGN_CD = 'BTQFR') >0 then b.que_id = '1' else FALSE end 

給出錯誤ORA-00905:缺少關鍵字

WHERE子句中使用CASE語句嘗試以下操作:

select *
from scores a, queues b 
where res_id = '112321'
and b.que_id = a.que_id
and case when (select count(qasgn_cd)
               from queues 
               where que_id = b.que_id 
               and QASGN_CD = 'BTQFR') > 0 
    then TRUE
    else FALSE
    end 

假設您的表如下:

create table "Table A" (   
   id  number, 
   bid number
);

insert into "Table A" values (1,  2);
insert into "Table A" values (1,  3);
insert into "Table A" values (2,  4);    
insert into "Table A" values (2,  5);    


create table "Table B" (   
   bid  number, 
   col2 varchar2(50)
);

insert into "Table B" values (2,    'ABC');
insert into "Table B" values (3,    'ABC');
insert into "Table B" values (4,    'ABC');
insert into "Table B" values (5,    'XYZ'); 

您可以按ID對數據進行分區,並區分包含“ XYZ”的分區和不包含“ XYZ”的分區。 在外部選擇中,您可以簡單地過濾結果。

select * 
  from (select a.*,
               b.col2,
               count(case when b.COL2 = 'XYZ' then 1 else null end) over (partition by a.ID) as cnt
          from "Table A" a
          join "Table B" b on b.BID = a.BID) t
 where (t.cnt = 0)
    or (t.cnt = 1 and t.col2 = 'XYZ');

您也可以在where子句中使用“ case when ...”,但在這種情況下則不必要。

select * 
  from (select a.*,
               b.col2,
               count(case when b.COL2 = 'XYZ' then 1 else null end) over (partition by a.ID) as cnt
          from "Table A" a
          join "Table B" b on b.BID = a.BID) t
 where case 
          when (t.cnt = 0) 
            or (t.cnt = 1 and t.col2 = 'XYZ') then 1 
          else NULL 
       end = 1; 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM