如何在oracle sql中创建条件where子句
表A拉回表B中的行。如果表B的col2是'XYZ',那么我只想要包含该id的XYZ的行如何在oracle sql中创建条件where子句,sql,oracle,conditional,Sql,Oracle,Conditional,表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 =
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
子句中使用大小写
语句尝试以下操作:
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;
使用
false
值将else
子句添加到案例/if中。例如:case when x then y else FALSE end
-如果返回FALSE,该行将从结果中丢弃,表示我缺少一个关键字,如果我在else语句中输入false,它会给出一个无效的错误用准确的代码更新您的问题并返回错误消息。您可以解释一下:从表b1中选择b.col2,其中b1.col=b.col1
-b.col2
来自b表还是b1表吗?为什么从b1表中选择b.col2列?感谢您指出这一点。我已经更新了代码,给出了ORA-00920:无效的关系运算符