2015-11-11 21 views
0

我正在尋找兩個不同表中兩列之間不一致的幫助。使用SUBSTR刪除前幾個和最後幾個字符,然後比較表列值

表1有ColumnA

表2具有ColumnB

ColumnA和ColumnB有需要進行比較之前先取出值,例如

ColumnA = TZ-ZA112 
ColumnA = TZ-RT322 
ColumnA = TZ-JKAAA 
ColumnB = TZ-ZA112,-2 
ColumnB = TZ-HHASS,-4 
ColumnB = TZ-RT322,4- 

所以基本上,我需要有TZ - (前三個)和##(後三個)在比較之前被刪除,那麼我需要讓查詢吐出兩列中不存在的值。那麼輸出應該是

HHASS 
JKAAA 

我會說實話,我不能完成我的周圍提前使用SUBSTR和INSTR在一起,而結合這些表產生這種輸出。

+0

前三個字符將始終是'TZ-'? – Nivas

+0

@Nivas不,他們不會,這只是一個例子。 – ceesharpie

回答

1

假設您將始終需要從第A列和第B列中的第4個字符開始,並且需要獲取substr,直到,字符的下面的代碼才起作用。

要獲取不在columnA和columnB中的值,請使用minus。對於不在列B和列A中的值,必須重複此操作。最後,請執行union以獲得所需的結果。

(select substr(columnA, 4, instr(columnA,',')-1) col from table1 
minus 
select substr(columnB, 4, instr(columnB,',')-1) col from table2 
) 
union all 
(select substr(columnB, 4, instr(columnB,',')-1) col from table2 
minus 
select substr(columnA, 4, instr(columnA,',')-1) col from table1 
) 
+0

你也介意在這裏解釋你如何使用substr和instr?謝謝! – ceesharpie

+0

如果列中的某個值中有多個逗號,該怎麼辦? – ceesharpie

+0

你會在上面的答案中得到第一個','的出現。如果你必須處理多個''',則查詢會變得複雜。如果您顯示一些示例數據,將更容易解釋 –

0

根據這個網站:http://www.dba-oracle.com/t_convert_set_to_join_sql_parameter.htm,具有不更換MINUS運算符子查詢更快。我希望看到這個證明。無論如何,我使用REGEXP_REPLACE,因爲我對嵌套的INSTR/SUBSTR調用過敏。

首先,我使用WITH子句來設置數據表1和表2作爲原始數據表(當然,您已經有了這些,因此不需要這部分)。注意我在那裏添加了一個嵌入逗號的附加行,以滿足OP中註釋的問題。然後,仍然使用WITH子句,我從相同的數據中創建了T1_converted和T2_converted,但從Table1/ColumnA剝離了前3個字符,並從Table2/ColumnB剝離了前3和後3個字符。這樣做會減少底部實際選擇中所需的REGEXP_REPLACE調用次數,並準備數據以使選擇更容易遵循。注 - 假設總是有3個主要字符在兩個表中剝離,3個尾隨字符剝離在表2中。如果這應該改變,正則表達式將不得不改變。

SQL> -- Simulates original table 
SQL> with Table1(ColumnA) as (
    2 select 'TZ-ZA112' from dual 
    3 union 
    4 select 'TZ-RT322' from dual 
    5 union 
    6 select 'TZ-JKAAA' from dual 
    7 ), 
    8 -- Simulates original table 
    9  Table2(ColumnB) as (
10 select 'TZ-ZA112,-2' from dual 
11 union 
12 select 'TZ-HHASS,-4' from dual 
13 union 
14 select 'TZ-RT322,4-' from dual 
15 union 
16 select 'TZ-R,T322,4-' from dual -- make sure commas are handled 
17 ), 
18 -- Strip leading 3 characters from table 1 
19  T1_converted(ColA) as (
20 select regexp_replace(ColumnA, '^.{3}(.*)$', '\1') from Table1 
21 ), 
22 -- Strip leading and trailing 3 characters from table 2 
23  T2_converted(ColB) as (
24 select regexp_replace(ColumnB, '^.{3}(.*).{3}$', '\1') from Table2 
25 ) 
26 -- Get the differences 
27 select ColA Unique 
28 from T1_converted 
29 where (ColA) not in 
30  (select ColB from T2_converted) 
31  union all 
32 select ColB from T2_converted 
33 where (ColB) not in 
34  (select ColA from T1_converted); 

輸出:

Unique 
----------------------------------------------------------------------------- 
JKAAA 
R,T322 
HHASS 

SQL> 

我沒有看到這個值,而不包括具有數據(或丟失數據?)表的名稱,但不是在你的要求,所以我會把它留給你作爲一個練習,以彌補出