【问题标题】:Combining select and select union in SQL Server在 SQL Server 中结合 select 和 select union
【发布时间】:2019-03-09 07:03:40
【问题描述】:

我有两张桌子

  • 具有 3 列的表 A:ID, NAME, VALUE 1
  • 表 B 有 3 列:ID, NAME, VALUE 2

表 A: 编号 : A1, A2 名称:AAA、BBB 值 1:1000,2000

表 B: 编号 : B1, B2 名称: CCC,DDD 价值 1:3000,4000

我想显示这样的结果:

ID、名称、值 1、值 2 A1 AAA 1000 A2 BBB 2000 A3 CCC 3000 A4 DDD 4000

我已经尝试过union,它适用于id, name 列。普通的select + union select呢,可以吗?

【问题讨论】:

  • 欢迎使用 stackoverflow(“SO”),我们可能很容易忘记我们对您的表或数据一无所知(我们无法猜测这些细节)。请提供每个表中的小数据样本,然后提供所需查询的预期结果
  • 您是否尝试过使用“union all”的答案?
  • 我已经尝试过 union all 但它给出了相同的结果
  • 我已经尝试过 union all 但它给出了相同的结果
  • 我不知道union all 方法会如何失败。它完全符合您的*预期结果see this answer

标签: sql sql-server


【解决方案1】:

你可以使用union all:

select id, name, value1, null as value2
from a
union all
select id, name, null as value1, value2
from b;

【讨论】:

    【解决方案2】:

    你也可以使用Full Outer Join

    SELECT a.id, a.name, a.value1, b.value2
    FROM tableA as a
    FULL OUTER JOIN tableB AS b ON
    a.id = b.id
    

    【讨论】:

      【解决方案3】:

      online demonstration

      MS SQL Server 2017 架构设置

      CREATE TABLE Table1
          ([ID] varchar(2), [NAME] varchar(3), [VALUE1] int)
      ;
      
      INSERT INTO Table1
          ([ID], [NAME], [VALUE1])
      VALUES
          ('A1', 'AAA', 1000),
          ('A2', 'BBB', 2000)
      ;
      
      
      CREATE TABLE Table2
          ([ID] varchar(2), [NAME] varchar(3), [VALUE2] int)
      ;
      
      INSERT INTO Table2
          ([ID], [NAME], [VALUE2])
      VALUES
          ('B1', 'CCC', 3000),
          ('B2', 'DDD', 4000)
      ;
      

      查询 1

      select id, name, value1, null as value2
      from table1
      union all
      select id, name, null as value1, value2
      from table2
      

      Results

      | id | name | value1 | value2 |
      |----|------|--------|--------|
      | A1 |  AAA |   1000 | (null) |
      | A2 |  BBB |   2000 | (null) |
      | B1 |  CCC | (null) |   3000 |
      | B2 |  DDD | (null) |   4000 |
      

      【讨论】:

      • Tengkyu 这么多,运行完美
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-07-23
      • 2018-07-11
      相关资源
      最近更新 更多