SQL 服务器程序 - 合并两个 table 不重复 - 如果 table B 列 B =1 那么
SQL Server procedure - Merge two tables without duplicates - if table B column B =1 then
我正在尝试合并 SQL 中的两个 table,不重复。如果值 = 1,我需要选择 Table B 列 B 的值。 Table A 是一个包含默认值的列表框,table B 包含每个用户的列表框值。
Table一个
Col_A Col_B
------------
701 null
702 null
703 null
704 null
Table B
Col_A Col_B
-------------
701 1
703 1
想要的结果
Col_A Col_B
-------------
701 1
702 null
703 1
704 null
你想要 left join
吗?
select a.col_a, b.col_b
from table_a a
left join table_b b on b.col_a = a.col_a
I need the values of Table B column B to be selected if the values=1
在您的示例数据中,table b 中的所有行都具有值 1
。如果您确实也想过滤值,则向 left join
:
添加另一个条件
select a.col_a, b.col_b
from table_a a
left join table_b b on b.col_a = a.col_a and b.col_b = 1
只有这两列,这似乎没什么用。如果你只是想知道 some row 是否存在于 table b 中,具有相同的 col_a
和值 1
,那么 exists
更合适:
select a.col_a,
case when exists (select 1 from tableb b where b.col_a = a.col_a and b.col_b = 1)
then 1
end as col_b
from table_a a
我正在尝试合并 SQL 中的两个 table,不重复。如果值 = 1,我需要选择 Table B 列 B 的值。 Table A 是一个包含默认值的列表框,table B 包含每个用户的列表框值。
Table一个
Col_A Col_B
------------
701 null
702 null
703 null
704 null
Table B
Col_A Col_B
-------------
701 1
703 1
想要的结果
Col_A Col_B
-------------
701 1
702 null
703 1
704 null
你想要 left join
吗?
select a.col_a, b.col_b
from table_a a
left join table_b b on b.col_a = a.col_a
I need the values of Table B column B to be selected if the values=1
在您的示例数据中,table b 中的所有行都具有值 1
。如果您确实也想过滤值,则向 left join
:
select a.col_a, b.col_b
from table_a a
left join table_b b on b.col_a = a.col_a and b.col_b = 1
只有这两列,这似乎没什么用。如果你只是想知道 some row 是否存在于 table b 中,具有相同的 col_a
和值 1
,那么 exists
更合适:
select a.col_a,
case when exists (select 1 from tableb b where b.col_a = a.col_a and b.col_b = 1)
then 1
end as col_b
from table_a a