表A拉回表B中的行。如果表B的col2是' XYZ'那么我只想要包含XYZ的行用于该id。
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:缺少关键字
答案 0 :(得分:0)
使用CASE
子句中的WHERE
语句尝试以下内容:
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
答案 1 :(得分: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;