2016-05-06 79 views
0

我有一个基地台与以下数据数据插入使用SQL/PLSQL

table1的

NUMBER  TYPE  DATE 
1   ABC   2015-05-05 10:00:00 
1   XYZ   2015-05-05 11:00:00 

我所需要的输出表 “测试” 为具有低于细节

id T1   TYPE_1 T2   TYPE_2 
1 10:00:00 ABC  11:00:00 XYZ 

我有以下尝试,但它不起作用。我是sql plsql的新手。

begin 

if exists (select distinct id from test where id in (select distinct NUMBER from table1)) 

    begin 

     update test set 

     T1 = 

     (
      case 
      when TYPE='ABC' then DATE end as T1 

     ) , 
     T2 = 
     (
      case 
      when TYPE='XYZ' then DATE end as T2 
     ) 
      where TA = table1.NUMBER 
    end 

else 

    begin 

     insert into test (
     T1, 
     T2 
     ) 
     select (
     case when TYPE='ABC' then DATE end as T1, 
     case when TYPE='XYZ' then DATE end as T2 
     ) 
     from table1 where NUMBER=test.id 
    end 
end 
+0

如果每个数字每种类型有多于一行,该怎么办? –

+0

每个类型每个编号不会超过1行 – tester

回答

0

试试这个,如果只是“ABC”的“XYZ”类型存在于表中:

SELECT number as id, 
     MAX(CASE WHEN Type = 'ABC' THEN Date ELSE NULL END) as T1, 
     MAX('ABC') as Type_1, 
     MAX(CASE WHEN Type = 'XYZ' THEN Date ELSE NULL END) as T2, 
     MAX('XYZ') as Type_2 
FROM T 
GROUP BY Number 
+0

有记录的十万个,因此它给出输出花费太多时间。 – tester

+0

并将其插入新行。我需要一行输出/记录 – tester

+0

,并且我们得到一个错误“ORA-00937”而不是单组功能 – tester

1

你有什么有所谓的UPSERT:在目标插入或更新行表,具体取决于它是否匹配源表中的一行。在Oracle中,我们可以使用MERGE语句在纯SQL实现这一目标:

merge into test 
using (select abc.number, abc.type as type_1, abc.date as t1 
       , xyz.type as type_2, xyz.date as t2 
     from table_1 abc 
       join table_2 xyz 
       on abc.number = xyz.number 
     where abc.type = 'ABC' 
     and xyz.type = 'XYZ' 
     ) t 
on (test.number = t.number 
when not matched then 
    insert (t.number, t.type_1, t.t1, t.type_2, t.t2) 
when matched then 
    update set test.t1 = t.t1 
       , test.t2 = t.t2 
/

子查询在using子句支点利用所需输出推断逻辑拖行成一个。您可能需要扩展此查询,具体取决于您将场景简化为在此处发布的次数。