簡體   English   中英

Oracle SQL:根據條件將某些記錄從一個表轉移到另一個過濾行

[英]Oracle SQL: Transfer certain records from one table to another filtering rows based on condition

需要將某些列的某些記錄從Table1傳輸到Table2 ,但需要根據條件過濾行。

假設Table1如下所示,其中有很多列。

Table1

A                 B                        C        D     E    F       G     H   ...
1    24-OCT-20 08.22.57.642000000 AM      100      xyz    1    1     
2    24-OCT-20 08.22.57.642000000 AM      100      xyz    1    0
13   25-OCT-20 05.47.52.733000000 PM      100      xyz    1    0
34   26-OCT-20 09.22.57.642000000 AM      100      xyz    1    0
25   26-OCT-20 09.25.57.642000000 AM      101      xyz    1    0
26   26-OCT-20 09.25.57.642000000 AM      101      xyz    1    1
6    26-OCT-20 09.25.57.642000000 AM      101      abc    1    1
10   26-OCT-20 09.25.57.642000000 AM      101      xyz    0    1
17   26-OCT-20 04.22.57.642000000 AM      100      xyz    1    0
18   26-OCT-20 06.22.57.642000000 AM      105      xyz    1    1
19   26-OCT-20 06.22.57.642000000 AM      105      xyz    1    0

在 Table2 中,需要根據以下情況從 Table1 中插入行:

首先, select A, B, C, D, E, F from Table1 where D='xyz' and E=1; 並在此查詢的結果上應用以下condition以進一步過濾掉不需要的行:

Condition: For same values in columns B, C, D & E in 2 different rows, if column F has 2 different values then only keep the row with greater value in column A.

因此,表 2 中所需的Table2如下所示:

Table2

A                 B                        C        D     E    F
2    24-OCT-20 08.22.57.642000000 AM      100      xyz    1    0
13   25-OCT-20 05.47.52.733000000 PM      100      xyz    1    0
34   26-OCT-20 09.22.57.642000000 AM      100      xyz    1    0
26   26-OCT-20 09.25.57.642000000 AM      101      xyz    1    1
17   26-OCT-20 04.22.57.642000000 AM      100      xyz    1    0
19   26-OCT-20 06.22.57.642000000 AM      105      xyz    1    0

如何通過最簡單最高效的 SQL 查詢來實現這一點?

任何幫助將不勝感激。

您可以使用 window 函數:

insert into table2 (a, b, c, d, e, f)
select a, b, c, d, e, f
from (
    select t1.*,
        row_number() over(partition by b, c, d, e order by a desc) rn
    from table1 t1
    where d = 'xyz' and e = 1
) t1
where rn = 1

這可以使用GROUP BYKEEP子句來實現,如下所示:

select max(t.a) as a, t.b, t.c, t.d, t.e,
       max(t.f) keep (dense_rank last over order by t.a) as f
  from t
 where t.d = 'xyz' and t.e = 1
group by t.b, t.c, t.d, t.e

暫無
暫無

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

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