Combining Two Tables With Oracle SQL

主宰稳场 提交于 2021-02-07 21:57:00

问题


I have two tables in the following structure:

TABLE 1:

ITEM  | JAN | FEB | MAR | APR | MAY | JUN
___________________________________________

Item A| 50  | 10  | 25  | NULL| NULL| NULL
Item C| 26  | 20  | 23  | NULL| NULL| NULL
Item B| 25  | 30  | 22  | NULL| NULL| NULL

TABLE 2:

ITEM  | JAN | FEB | MAR | APR | MAY | JUN
___________________________________________

Item A| NULL| NULL| NULL|  32 | 26  | 12
Item B| NULL| NULL| NULL|  25 | 24  | 10
Item D| NULL| NULL| NULL|  22 | 35  | 14

I am trying to merge the tables, to get the following result:

ITEM  | JAN | FEB | MAR | APR | MAY | JUN
___________________________________________

Item A| 50  | 10  | 25  |  32 | 26  | 12
Item B| 25  | 30  | 22  |  25 | 24  | 10
Item C| 26  | 20  | 23  | NULL| NULL| NULL
Item D| NULL| NULL| NULL|  22 | 35  | 14

I tried the following query:

MERGE INTO TABLE1 a USING (
  SELECT REBATE_ITEM, JAN, FEB, MAR, APR, MAY  FROM TABLE2
)  b
ON (TRIM(a.ITEM) = TRIM(b.ITEM) AND a.JUN is null)
WHEN  MATCHED THEN
  UPDATE SET 
    a.APR = b.APR, 
    a.MAY = b.MAY,     
    a.JUN = b.JUN

I get the following result: SQL Error: ORA-38104: Columns referenced in the ON Clause cannot be updated:

Any ideas on how I can accomplish this merge/join/whatever?


回答1:


Give this a try, I think it should work for what you are trying to do.

MERGE INTO TABLE1 a USING (
    SELECT ITEM, JAN, FEB, MAR, APR, MAY, JUN
    FROM TABLE2) b
ON (a.ITEM = b.ITEM)
WHEN MATCHED THEN
    UPDATE SET
        a.APR = b.APR,
        a.MAY = b.MAY,
        a.JUN = b.JUN
    WHERE a.JUN = null
WHEN NOT MATCHED THEN
    INSERT (a.ITEM, a.JAN, a.FEB, a.MAR, a.APR, a.MAY, a.JUN)
    VALUES (b.ITEM, b.JAN, b.FEB, b.MAR, b.APR, b.MAY, b.JUN);



回答2:


If you just want to select the values (rather than actually changing data in the database) you can use a union and a group by:

select ITEM, 
       sum(JAN) as jan, 
       sum(FEB) as feb, 
       sum(MAR) as mar,
       sum(APR) as apr,
       sum(may) as may  
       sum(JUN) as jun
from (
   select ITEM, JAN, FEB, MAR, APR, MAY, JUN
   from table1
   union all
   select ITEM, JAN, FEB, MAR, APR, MAY, JUN
   from table2
) t
group by item;


来源:https://stackoverflow.com/questions/18408425/combining-two-tables-with-oracle-sql

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!