我有 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)
uj5u.com熱心網友回復:
您可以選擇要從每個表中獲取的預期列:
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
uj5u.com熱心網友回復:
您可以在子查詢中使用UNION ALL ,然后使用GROUP BY。
這將在沒有價值的地方給你零。如果這是一個問題,我們可以修改演示文稿。
如果你有另一張桌子上所有玩家,我們可以讓我們LEFT JOIN 加入到三張桌子上
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;
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/460714.html
上一篇:短路表
