如何使用不同的字段值组合两列

时间:2015-02-13 23:40:19

标签: sql sql-server database

我在sql server

中有两个来自不同选择的列

表1

 ID     Name           Bit
....   ............   .....
 1     Enterprise 1   False 
 2     Enterprise 2   True
 3     Enterprise 3   False 

表2

 ID       Name             Bit 
....    ............     .......
 1      Enterprise 1      True
 2      Enterprise 2      False
 3      Enterprise 3      False 

预期结果

ID       Name           Bit 
....   ............   ......
1      Enterprise 1    True
2      Enterprise 2    True
3      Enterprise 3    False 

问题是在两个表之间建立联合,并且位列为prev的字段为真

有什么想法吗?

3 个答案:

答案 0 :(得分:1)

您可以在另一个表上进行左连接,以排除应从另一个表中使用的记录:

select
  t1.ID, t1.Name, t1.Bit
from
  [Table 1] t1
  left join [Table 2] t2 on t2.ID = t1.ID
where
  t1.Bit = 1 or t2.Bit = 0

union all

select
  t2.ID, t2.Name, t2.Bit
from
  [Table 2] t2
  left join [Table 1] t1 on t1.ID = t2.ID
where
  t1.bit = 0 and t2.Bit = 1

(如果两个表中都有True或两个表中都有False,则会使用来自Table 1的记录。)

答案 1 :(得分:1)

我建议将它转换为int:

select id, name, cast(max(bitint) as bit) as bit
from ((select id, name, cast(bit as int) as bitint
       from table1
      ) union all
      (select id, name, cast(bit as int) as bitint
       from table2
      )
     ) t12
group by id, name;

使用您的数据,您也可以使用join

执行此操作
select t1.id, t1.name, (t1.bit | t2.bit) as bit
from table1 t1 join
     table2 t2
     on t1.id = t2.id and t1.name = t2.name;

这假设两个表之间的所有行匹配(如示例数据中所示)。如果他们不这样做,您可以使用full outer join执行类似操作。

答案 2 :(得分:0)

SELECT Table1.ID, Table1.Name, IIF(Table1.[Bit]>0 OR Table2.[Bit]>0,1,0) AS [Bit]
FROM 
(VALUES(1,'Enterprise 1',0),(2,'Enterprise 2',1),(3,'Enterprise 3',0)) as Table1(ID,Name,Bit),
(VALUES(1,'Enterprise 1',1),(2,'Enterprise 2',0),(3,'Enterprise 3',0)) as Table2(ID,Name,Bit)
WHERE Table1.ID = Table2.ID

在我看来,您只是在Bit列上执行逻辑或运算,并将其称为UNION。

Query Result