3

我有以下结构的两个表:

表格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

表 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

我正在尝试合并表,以获得以下结果:

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

我尝试了以下查询:

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

我得到以下结果: SQL 错误:ORA-38104:无法更新 ON 子句中引用的列:

关于如何完成此合并/加入/无论如何的任何想法?

4

2 回答 2

8

试一试,我认为它应该适用于您正在尝试做的事情。

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);
于 2013-08-23T18:31:11.113 回答
1

如果您只想选择值(而不是实际更改数据库中的数据),您可以使用联合和组:

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;
于 2013-08-23T17:26:30.730 回答