SQL Oracle,合并两个结果集

时间:2019-04-10 18:37:43

标签: sql oracle datatable

我有两个表,没有键可以将它们联接起来。

第一个结果:

select fruit, sum(sales) from normal
group by fruit

预期答案

 Red Apple        5000

 Yellow Mango     7000

第二结果:

select fruit, sum(sales) from not_normal
group by fruit

预期答案

 Green Apple   300
 Green Mango   500

现在,我要以这种格式显示最终结果:

enter image description here

我可以提取结果1和结果2,并在Excel上进行操作。但是我想知道如何在Oracle SQL中做到这一点。

1 个答案:

答案 0 :(得分:2)

你知道这是怎么回事...进垃圾,出垃圾。

SQL> with
  2  normal (fruit, sales) as
  3    (select 'red apple', 5000 from dual union all
  4     select 'yellow mango', 7000 from dual
  5    ),
  6  not_normal (fruit, sales) as
  7    (select 'green apple', 300 from dual union all
  8     select 'green mango', 500 from dual
  9    )
 10  select n.fruit as fruit,
 11         sum(n.sales) nsales,
 12         nn.fruit as fruit_1,
 13         sum(nn.sales) nnsales,
 14         regexp_substr(n.fruit, '\w+$') as fruits,
 15         sum(n.sales) + sum(nn.sales) sales
 16  from normal n join not_normal nn
 17    on regexp_substr(n.fruit, '\w+$') = regexp_substr(nn.fruit, '\w+$')
 18  group by n.fruit, nn.fruit
 19  /

FRUIT            NSALES FRUIT_1        NNSALES FRUITS                    SALES
------------ ---------- ----------- ---------- -------------------- ----------
red apple          5000 green apple        300 apple                      5300
yellow mango       7000 green mango        500 mango                      7500

SQL>