有三个表,每个表都有一列名称,例如
目标是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'的列,例如
期望的结果是:
Name | Table1 | Table2 | Table3 | Company
A | 1 | 1 | 1 | XYZ
B | 1 | 1 | 0 | ''
C | 1 | 0 | 1 | ZYX
我没有成功......
答案 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
只有一个值。