2016-05-06 52 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子句支點利用所需輸出推斷邏輯拖行成一個。您可能需要擴展此查詢,具體取決於您將場景簡化爲在此處發佈的次數。