将两个表与Oracle SQL结合使用

时间:2013-08-23 17:21:15

标签: sql oracle

我在以下结构中有两个表:

表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子句中引用的列:

关于如何完成此合并/加入/其他任何想法?

2 个答案:

答案 0 :(得分:6)

尝试一下,我认为它应该适用于你想要做的事情。

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);

答案 1 :(得分:1)

如果您只想选择值(而不是实际更改数据库中的数据),您可以使用union和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;