简体   繁体   English

连接结构相似的3张桌子

[英]Joining 3 tables with similar structure

I'm executing sql queries in oracle 10g. 我正在oracle 10g中执行sql查询。

I want to join 3 tables into a single new table containing all the records from the 3 individual tables. 我想将3个表连接到一个包含3个单独表中所有记录的新表中。 The balance should be Summed up wherever the reg_id is duplicated between the 3 tables, such that there is just one entry per reg_id with the summed balance in my new table. 只要在3个表之间重复reg_id的地方,余额就应该加起来,这样每个reg_id只能有一个条目,而新表中的余额就是总和。

Sample data ( similar tables, with different values ) . 样本数据(相似的表,具有不同的值)。 tables : temp1, temp2, temp3 表格:temp1,temp2,temp3

reg_id    |            balance
--------------------------------
92603013               183.77
92611902               419.46
92766121               77.04
93527720               24.84
93581368               120.09
93684684                89.88
93527720               113.66

Appreciate if someone can help me with the syntax. 如果有人可以在语法方面帮助我,不胜感激。

Try the following... 尝试以下...

INSERT INTO target_table (reg_id, balance)
SELECT reg_id, sum(balance) as balance
FROM (select reg_id, balance from temp1
      UNION ALL
      select reg_id, balance from temp2
      UNION ALL
      select reg_id, balance from temp3)
GROUP BY reg_id;

I haven't tried it so don't know if the syntax is correct and whether it'll will horribly mangle your data. 我还没有尝试过,所以不知道语法是否正确以及它是否会严重破坏您的数据。 :) :)

EDIT: Changed UNION to UNION ALL. 编辑:将UNION更改为UNION ALL。 Thanks, APC! 谢谢,APC!

EDIT 2: Specified the columns explicitly per Tony's recommendation. 编辑2:根据托尼的建议明确指定列。

I'd suggest: 我建议:

SELECT coalesce(t1.reg_id, t2.reg_id, t3.reg_id) AS the_reg_id,
       coalesce(t1.balance, 0.0) + 
       coalesce(t2.balance, 0.0) +
       coalesce(t3.balance, 0.0) AS the_balance
FROM t1 FULL OUTER JOIN t2 ON (t1.reg_id = t2.reg_id)
        FULL OUTER JOIN t3 ON (t1.reg_id = t3.reg_id)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM