SQL新手,我想创建一个结合两个表的新表。我试图使用插入选择查询来创建一个新表。所以假设以下
Jan Table
C_ID Total_Amount
1 10
2 3
3 5
2月表
C_ID Total_Amount
1 4
4 22
5 6
我想要决赛桌
C_ID Jan_Amount Feb_Amount
1 10 4
2 3 0
3 5 0
4 0 22
5 0 6
我的SQL语句是
insert into Final
select Jan.C_ID, Jan.Total_Amount, Feb.Total_amount
from Jan
full outer join Feb on Jan.C_ID = Feb.C_ID
问题在于,当我执行select Jan.C_ID
时,它不会包含来自Feb表的客户ID 4和5。
解决此问题的正确方法是什么?
答案 0 :(得分:2)
你可以使用联合所有例如:
加入表格alos insert into Final
select C_ID, ifnull(jan_Total_Amount,0), ifnull(feb_Total_amount,0)f
from (
select Jan.C_ID, Jan.Total_Amount as jan_Total_Amount, null as feb_Total_amount
from jan
union all
select fed.C_ID, null, feb.Total_Amount
from feb
) t
为了获得相同C_ID的两个值,你可以使用(假)聚合函数和分组
insert into Final
select C_ID, min(jan_Total_Amount), feb_Total_amount
from (
select C_ID, ifnull(jan_Total_Amount,0) jan_Total_Amount , ifnull(feb_Total_amount,0) feb_Total_amount
from (
select Jan.C_ID, Jan.Total_Amount as jan_Total_Amount, null as feb_Total_amount
from jan
union all
select fed.C_ID, null, feb.Total_Amount
from feb
) t
)t2
group by C_ID
答案 1 :(得分:0)
您可以left join
right join
和Union
insert into Table_3 (C_ID,Jan_Amount, Feb_Amount)
select T1.C_ID,T1.Total_Amount, T2.Total_Amount from Jan T1 left join Feb T2 ON T1.C_ID = T2.C_ID
UNION
select T2.C_ID,T1.Total_Amount, T2.Total_Amount from Jan T1 right join Feb T2 ON T1.C_ID = T2.C_ID
where T1.C_ID is null