联合三个表并显示数据来自何处(扩展)

时间:2014-08-18 13:56:22

标签: sql union

有三个表,每个表都有一列名称,例如

  • 表1 - 列名称'名称' - 价值观' A',' B'和' C'
  • 表2 - 列名'名称' - 价值观' A'和' B'
  • 表3 - 列nane'名称' - 价值观' A'和' C'

目标是UNION表 - 三个表的每个值只应显示一次。此外,应该有三个新的"虚拟列"显示包含值的表格(' 1'包含值时,' 0'如果不包含)。所以结果应该是这样的:

  Name| Table1 | Table2 | Table3
  A   |    1   |    1   |    1
  B   |    1   |    1   |    0
  C   |    1   |    0   |    1

这方面的工作解决方案是:

select Name, max(Table1) as Table1, max(Table2) as Table2, max(Table3) as Table3
from (select Name, 1 as Table1, 0 as Table2, 0 as Table3
      from table1
      union all
      select Name, 0 as Table1, 1 as Table2, 0 as Table3
      from table2
      union all
      select Name, 0 as Table1, 0 as Table2, 1 as Table3
      from table3
     ) t
group by Name;

现在应该在表1中再说一个名为' Company'的列,例如

  • 表1 - 列名称'名称' - 价值观' A',' B'和' C',列名'公司' - 价值观' XYZ','',' ZYX'
  • 表2 - 列名'名称' - 价值观' A'和' B'
  • 表3 - 列nane'名称' - 价值观' A'和' C'

期望的结果是:

Name | Table1 | Table2 | Table3 | Company
   A | 1 | 1 | 1 | XYZ
   B | 1 | 1 | 0 | ''
   C | 1 | 0 | 1 | ZYX

我没有成功......

1 个答案:

答案 0 :(得分:0)

只需将其添加到每个子查询,然后添加到外部查询:

select Name, max(Table1) as Table1, max(Table2) as Table2, max(Table3) as Table3,
       max(Company) as Company
from (select Name, 1 as Table1, 0 as Table2, 0 as Table3, Company
      from table1
      union all
      select Name, 0 as Table1, 1 as Table2, 0 as Table3, NULL as Company
      from table2
      union all
      select Name, 0 as Table1, 0 as Table2, 1 as Table3, NULL as Company
      from table3
     ) t
group by Name;

注意:这假设公司每个Name只有一个值。