2016-02-19 63 views
0

表A拉回表B中的行。如果表B的col2是'XYZ',那麼我只需要包含該yy的XYZ的行。如何在oracle中創建條件where子句sql

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行總共兩行編號1和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:缺少關鍵字

+0

爲您的案例添加'else'子句/如果使用'false'值。例如:'case when x then y else FALSE end' - 如果返回false,則該行將從結果中被丟棄 –

+0

它說我錯過了一個關鍵詞,如果我在else語句中放置false,它會給出一個無效錯誤 – user1854438

+0

用確切代碼更新您的問題並返回錯誤消息 –

回答

0

嘗試類似的東西在你的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 
+0

這給了ORA-00920:無效的關係運算符 – user1854438

0

假設你的表是如下:

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;