对不起,标题可能会令人困惑,但我会在这里尝试解释一下。所以我有2张桌子。
Table1
Name
Int
Decimal
Table2
Name
Int
Decimal
我正在尝试将数据合并到第三个表中。它看起来像这样
Table3
Name
Table1_Int
Table1_Decimal
Table2_Int
Table2_Decimal
插入不是问题。问题是我有一些名称存在于一个表中而不是另一个表中。我仍然希望这些显示,只有NULL值,没有值。
这是我的存储过程
IF NOT EXISTS(
SELECT Name FROM Table3)
INSERT INTO Table3(
Name,
Table1_Int,
Table1_Decimal,
Table2_Int,
Table2_Decimal)
SELECT
t.Name,
AVG(t.Int) as Table1_Int,
AVG(CAST(t.Decimal as decimal(6,2))) as Table1_Decimal
AVG(a.Int) as Table2_Int,
AVG(CAST(a.Decimal as decimal(6,2))) as Table2_Decimal
FROM Table1 t
JOIN Table2 a
ON t.Name = a.Name
GROUP BY t.Name
ELSE
UPDATE Table3
SET Name = Name
无论如何,我可以抓住所有名字,无论它们是否在表格之间匹配?
答案 0 :(得分:1)
我会选择FULL OUTER JOIN的基本逻辑。我希望它看起来像这样;
SELECT
COALESCE(t.name, a.name) name
,AVG(t.Int) t_int
,AVG(CAST(t.Decimal as decimal(6,2))) t_decimal
,AVG(a.Int) a_int
,AVG(CAST(a.Decimal as decimal(6,2))) a_decimal
FROM Table1 t
FULL OUTER JOIN Table2 a
ON t.name = a.name
GROUP BY COALESCE(t.name, a.name)