ms sql 服务器中超过两个 table 的完全外部合并,以准备所需的 table,如示例所示

Full outer merge of more than two tables in ms sql server to prepare desired table as shown in the example

我有 3 个表,如下所示。

t1:

id     runs
001    1200
020    600
123    1500

t2:

id     wickets
008    4
030    7
123    0
020    6   

t3:

id     catches
007    4
030    
123    2
040    6   

我想对所有三个表执行 FULL OUTER JOIN 并准备如下所示。

预期输出:

id     runs      wickets     catches
001    1200
020    600       6
123    1500      0           2
008              4
030              7
007                          4
040                          6

我试过下面的代码但没有用。

SELECT *
FROM t1
FULL OUTER JOIN t2
ON t1.id = t2.id
FULL OUTER JOIN t2.id = t3.id

我使用 pandas 使用以下代码做了同样的事情并且效果很好。

from functools import reduce
dfl=[t1, t2, t3]
df_merged = reduce(lambda  left,right: pd.merge(left,right,on=['id'],
                                            how='outer'), dfl)

您可以在 sub-query 中使用 UNION ALL,然后 GROUP BY.
这会给你没有价值的零。如果这是一个问题,我们可以修改演示文稿。
如果你有另一个 table 和所有玩家,我们可以 LEFT JOIN 到三个 table 和
WHERE runs <>'' OR wickets <> '' OR catches <> ''

select
sum(runs) "runs",
sum(wickets) "wickets",
sum(catches) "catches) 
from(
select id, runs, 0 wickets, 0 catches from t1
  union all
select id, 0, wickets,0 from t2
  union all
select id, 0,0, catches from t3
)
group by id,
order by id;

您可以 select 您希望从每个 table 获得的预期列:

SELECT coalesce(t1.id,t2.id, t3.id), t1.runs, t2.wickets, t3.catches
FROM  t1
FULL OUTER JOIN  t2 ON t1.id = t2.id
FULL OUTER JOIN  t3 ON COALESCE(t1.id, t2.id) = t3.id