gpt4 book ai didi

sql - 为两个表之间的公共(public)行添加标志

转载 作者:行者123 更新时间:2023-12-04 20:48:43 24 4
gpt4 key购买 nike

我有两个表说 A 和 B。B 是 A 的一个子集。我想做的是:向表 A 添加一个标志列(仅用于查看,不永久在表中)和这个值对于 A 和 B 之间的公共(public)行,标志应该是 yes,对于非公共(public)行,标志应该是 no。例如:

A table
Column1 Column2 Column3
X1 X2 X3
Y1 Y2 Y3
Z1 Z2 Z3

select * from A where column1=Y1; to get B

现在我的最终输出应该是

Column1 Column2 Column3 FLAG
X1 X2 X3 NO
Y1 Y2 Y3 YES
Z1 Z2 Z3 NO

我必须在 1 个 sql 语句(提取 B 并添加标志)中处理代码块下方的所有内容。我只能提取B。无法添加标志

使用oracle 11.2.0.2.0,sqlplus

最佳答案

使用外连接有条件地链接表 A 和 B,然后使用 CASE() 语句测试 A 中的给定行是否与 B 中的行匹配。

select a.*
, case when b.column1 is not null then 'YES' else 'NO' end as flag
from a left outer join b
on a.column1 = b.column1

请注意,这仅在只有 0 个或 1 个 B.COLUMN1 实例时才能正常工作。如果 B 包含 COLUMN1 的任何值的多个实例,那么您可以使用此变体:

select a.*
, case when b.column1 is not null then 'YES' else 'NO' end as flag
from a left outer join ( select distinct column1 from b ) b
on a.column1 = b.column1

关于sql - 为两个表之间的公共(public)行添加标志,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11502753/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com