【问题标题】:How make a union of two columns with different value of fields如何将具有不同字段值的两列合并
【发布时间】:2018-07-19 20:50:42
【问题描述】:

我在 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 

问题是在两个表之间建立一个联合,并且位列占主导地位的字段是真的

有什么想法吗?

【问题讨论】:

  • 第三条记录应该来自Table 1还是Table 2?一个项目可以在两个表中都有True,在这种情况下应该使用哪一个?
  • 来自两个不同选择的表格,选择很长,无法发布它们

标签: sql sql-server database


【解决方案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 做类似的事情。

【讨论】:

  • 第二个选项“from table1 t1 join table2 t2”中缺少 t1 和 t2 别名
  • :) 很高兴。看到正在使用的“按位或”也很高兴
【解决方案2】:

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

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 的记录。)

【讨论】:

    【解决方案3】:
    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 列上进行逻辑 OR 运算并将其称为 UNION。

    【讨论】:

      猜你喜欢
      • 2019-08-27
      • 1970-01-01
      • 1970-01-01
      • 2017-08-30
      • 2021-08-21
      • 1970-01-01
      • 1970-01-01
      • 2021-11-30
      • 1970-01-01
      相关资源
      最近更新 更多