表1
name closedid
rere 4
trtr 5
ewew 6
和 表2
name openedid
rere 6
trtr 7
ytyt 8
uyuy 5
和
table-3
name assign
rere 6
ytyt 8
uyuy 5
rtyy 9
和 表4
name unassign
rere 6
trtr 7
errt 5
hdtg 9
我想要这样的最终输出:
name closedid opened assign unassign
rere 4 6 6 6
trtr 5 7 null 7
ytyt null 8 8 null
uyuy null 5 5 null
ewew 6 null null null
rtyy null null 9 null
errt null null null 5
hdtg null null null 9
答案 0 :(得分:4)
我想,这就是你要找的东西:
SELECT coalesce(t1.NAME, t2.NAME, t3.NAME, t4.NAME) NAME
,t1.closedid
,t2.openedid
,t3.assign
,t4.unassign
FROM [table-1] t1
FULL OUTER JOIN [table-2] t2 ON t1.NAME = t2.NAME
FULL OUTER JOIN [table-3] t3 ON isnull(t1.NAME, t2.NAME) = t3.NAME
FULL OUTER JOIN [table-4] t4 ON coalesce(t1.NAME, t2.NAME, t3.NAME) = t4.NAME
答案 1 :(得分:1)
我会抓住所有不同的名字,然后对该列表进行左连接,这样可以更容易理解发生了什么。
;WITH cte(name)
AS (
SELECT name FROM table1
UNION
SELECT name FROM table2
UNION
SELECT name FROM table3
UNION
SELECT name FROM table4
)
SELECT
cte.name,
table1.closedid,
table2.openid,
table3.assign,
table4.unassign
FROM
cte
LEFT JOIN table1 ON cte.name = table1.name
LEFT JOIN table2 on cte.name = table2.name
LEFT JOIN table3 on cte.name = table3.name
LEFT JOIN table4 on cte.name = table4.name
答案 2 :(得分:0)
UNION
获取明确的名单LEFT JOIN
检索您的数据示例:
SELECT list.name, t1.assigned, t2.unsassigned, t3.closed, t4.open
FROM
(select name from table1
union select name from table2
union select name from table3
union select name from table4
) list
LEFT JOIN table1 t1 ON (list.name = t1.name)
LEFT JOIN table2 t2 ON (list.name = t2.name)
LEFT JOIN table3 t3 ON (list.name = t3.name)
LEFT JOIN table4 t4 ON (list.name = t4.name)
答案 3 :(得分:-1)
select coalesce(t1.name,t2.name,t3.name,t4.name) name, t1.closeid, t2.openid, t3.assign, t4.unassign
from table-1 t1
full outer join table-2 t2 on t1.name = t2.name
full outer join table-3 t3 on t2.name = t3.name
full outer join table-4 t4 on t3.name = t4.name
答案 4 :(得分:-1)
select
n.name, t1.closedid, t2.openedid, t3.assign, t4.unassign
from
(select name from [table-1]
union
select name from [table-2]
union
select name from [table-3]
union
select name from [table-4]
) as n
left join [table-1] t1 on n.name = t1.name
left join [table-2] t2 on n.name = t2.name
left join [table-3] t3 on n.name = t3.name
left join [table-4] t4 on n.name = t4.name