Oracle中union all小例

问题

想要将两个表中记录进行合并成一个表。
tableA中字段prov,city,ain,aout
tableB中字段prov.city,bin.bout
整合表tableC中字段prov,city,ain,aout.bin,bout

方案

使用union all:

CREATE TABLE tableC AS
SELECT A.PROV AS PROV,
       A.CITY AS CITY,
       A.IN   AS AIN,
       A.OUT  AS AOUT,
       0      AS BIN,
       0      AS BOUT
  FROM TABLEA A
UNION ALL
SELECT B.PROV AS PROV,
       B.CITY AS CITY,
       0      AS AIN,
       0      AS AOUT,
       B.IN   AS BIN,
       B.OUT  AS BOUT
  FROM TABLEB B

要注意的是,对于tableA中缺少的字段,要通过0来补充

TIPS

  • union all时,要保证顺序一致union all不会通过别名来调整顺序
  • 在对tableC进行查询时,要在分组后拿到SUM(ain)SUM(bin)不能同时为0的。
  • 通过HAVING SUM(ain) > 0 OR SUM(bin) > 0解决
    在HAVING语句中,可以使用ORAND操作
    分组前使用WHERE分组后使用HAVING

你可能感兴趣的:(Oracle中union all小例)