簡體   English   中英

Oracle 12c - 在插入選擇中從 1 條記錄中創建兩條記錄

[英]Oracle 12c - Creating two records out of 1 record in an insert select

我有一個插入選擇查詢,它帶回大約 100 萬條記錄,每條記錄大約有 30 列,有兩列(性能總計,機械總計)。 其中一列將有一個值。 Performance Total 可能有 nulll 值,mechanical total 可能有 null 值,或者兩者都有該記錄的值。

當記錄在兩列(性能總計、機械總計)中都有值時,我希望 SQL 查詢創建兩條記錄,因此將兩條記錄插入到一​​個表中而不是一個。 一項記錄是性能記錄,一項記錄是機械記錄。 性能總計或機械總計將插入到有總計字段的表中。

如何在不創建 UNION 語句的情況下在 SQL 查詢中完成此操作,因為它會導致性能問題?

我不認為這比使用 UNION 更有效率,但你可以這樣做:

insert into target (a, b, c, rec_type, rec_total)
select mt.a, mt.b, mt.c,
       case when r.rec = 1 then 'PERFORMANCE' else 'MECHANICAL' end 
       case when r.rec = 1 then mt.perf_total else mt.mech_total end 
from mytable mt
    cross join (select rownum rec from dual connect by level <= 2) r
where (mt.perf_total is not null and r.rec=1)
or (mt.mech_total is not null and r.rec = 2);

您正在描述union all

select . . . , 'performance' as which, performance_total
from t
where performance_total is not null
union all
select . . . , 'mechanical' as which, mechanical_total
from t
where mechanical_total is not null;

這確實需要掃描表兩次。 我不確定這對具有一百萬行的基表是否如此重要,它應該適合內存。

如果是這樣(如果表真的是一個視圖,則尤其如此),那么我會將逆樞軸表述為:

select . . . , pm.which,
       (case when which = 'performance' then performance_total
             else mechanical_total
        end)
from t cross join
     (select 'performance' as which from dual union all
      select 'mechanical' as which from dual 
     ) pm
where (case when which = 'performance' then performance_total
            else mechanical_total
       end) is not null;

或者,在最新版本的 Oracle 中,使用橫向連接:

select . . . , pm.which, pm.total
from t cross join lateral
     (select 'performance' as which, performance_total as total from dual union all
      select 'mechanical' as which, mechanical_total from dual 
     ) pm
where total is not null;

只是為了讓您知道我在我的唱片中使用了 UNPIVOT,它最終奏效了。

SELECT TYPE_OF_RECORD, RECORD_POINTS, 28 columns 
FROM ( SELECT PERF_TOTAL, MECH_TOTAL, 28 columns 
       FROM TABLE   UNPIVOT (RECORD_POINTS FOR TYPE_OF_RECORD  IN
                             (PERF_TOTAL AS 'PERF',
                              MECH_TOTAL AS 'MECH'))  
       WHERE RECORD_POINTS > 0
 ) X;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM