嗨朋友我在oracle中加入表时遇到问题我的表格如下所示
table1看起来像
id Name Jan
7001 Deven 22
7002 Clause 55
7004 Monish 11
7010 Dipesh 55
7070 Dipika 100
table2看起来像
id Name Feb
7001 Deven 12
7002 Clause 15
7003 Nimesh 20
7004 Monish 21
7005 Ritesh 22
表3看起来像
id Name Mar
7001 Deven 122
7020 Chalse 155
7003 Nimesh 88
7033 Monica 217
7070 Dipika 180
像这样我从12月到12月有12张桌子,我可以把它结合起来,然后像下面一样拿出来:
id Name Jan Feb Mar ...................... Dec
7001 Deven 22 12 122
7002 Clause 55 15 - .......................-
7003 Nimesh - 20 88 .......................2
7004 Monish 11 21 - .......................-
7005 Ritesh - 22 - .......................20
7010 Dipesh 55 - - .......................-
7020 Chalse - - 155 .......................-
7033 Monica - - 217 .......................100
7070 Dipika 100 - - .......................-
答案 0 :(得分:2)
我会选择没有连接的GROUP BY(可能效率最高,因为每个表都有一个传递 - GROUP BY子句将重复删除):
select id, name, max(jan) jan, max(feb) feb, /*...*/ max(dec) dec
from (select id, name, jan jan, null feb, /*...*/ null dec
from table1
union all
select id, name, null jan, feb feb, /*...*/ null dec
from table2
union all
/*...*/
select id, name, null jan, null feb, /*...*/ dec dec
from table12)
group by id, name
答案 1 :(得分:0)
我的方法是创建一个包含所有ID和名称的派生表,然后使用它来连接每个表。与UNION ALL
不同,UNION
会删除重复项:
select a.id, a.name, t1.Jan, t2.Feb, t3.Mar
from (
select id, name from table1
union
select id, name from table2
union
select id, name from table3
) a
left outer join table1 t1 on a.id = t1.id
left outer join table2 t2 on a.id = t2.id
left outer join table3 t3 on a.id = t3.id
答案 2 :(得分:0)
您可以考虑将所有一个表都列为列:“id,Name,Month,Quantity”(如果您要跨越多年,那么甚至一年)。