UNION ALL Trick ORACLE

时间:2017-07-14 17:08:10

标签: sql oracle

这可能很容易,但我无法弄清楚我该怎么办。

所以我的代码就像这样

例如

SELECT id,total,total2
FROM  (select id,  0  AS total ,t1.total AS total2
       FROM table1 t1
       union ALL
       select id, t2.total AS total, 0 AS total2
       FRoM table2 t2)

显示

id------total------totals
001      0           20
001      15          0

我想像这样展示

id------total------totals
001      15         20

我该怎么做?

非常感谢

2 个答案:

答案 0 :(得分:4)

之后进行汇总:

SELECT id, sum(total) as total, sum(total2) as total2
FROM  (select id,  0  AS total ,t1.total AS total2
       FROM table1 t1
       union ALL
       select id, t2.total AS total, 0 AS total2
       FRoM table2 t2
     ) i
GROUP BY id;

答案 1 :(得分:1)

您可以使用WITH和子查询从不同的Id列表中检索匹配Id中所有记录的总和,而不是将0转储到某些列作为填充。

strict digraph {

  rankdir=RL;
  node [shape=none, style=filled, fillcolor=aliceblue, fontname=verdana];

  Model [shape=none, label=<<table border="0" cellspacing="0">
    <tr><td border="1" bgcolor="lightblue">Model</td></tr>
    <tr><td border="1" align="left">Name</td></tr>
    <tr><td border="1" align="left">Description</td></tr>
    <tr><td border="1" align="left">Universe</td></tr>
  </table>>];

  Universe [shape=none, label=<<table border="0" cellspacing="0">
    <tr><td border="1" bgcolor="lightblue">Universe</td></tr>
    <tr><td border="1" align="left">Name</td></tr>
    <tr><td border="1" align="left">Description</td></tr>
  </table>>];

  Model -> Universe

}