2013-02-21 33 views
0

的錯配數量兩個表我有兩個表:加入與行

OLD_TABLE(OT)

Record_id | Name | Sequence_num 
------------------------------------ 
    78  | Austin | 0 
    78  | Mike | 1 
    78  | Joe | 2 

NEW_TABLE(NT)

Record_id | Name | Sequence_num 
------------------------------------ 
    78  | Mike | 0 
    78  | Joe | 1 
    78  | Austin | 2 
    78  | Fred | 3 
    78  | Ben | 4 

我」 m尋找是輸出表看起來像這樣:

Record_id | OT_Name | NT_Name | Sequence_num 
--------------------------------------------------- 
    78  | Austin | Mike  | 0 
    78  | Mike  | Joe  | 1 
    78  | Joe  | Austin | 2 
    78  | NULL  | Fred  | 3 
    78  | NULL  | Ben  | 4 

問題是我不知道每個表中有多少行。 OT可以有10行,NT可以有3個,或者NT可以有超過OT,或者他們可以有相同的數字。任何在對向表中沒有匹配Sequence_num的行都需要在適當的列中有一個NULL值。在這種情況下,沒有爲每個表創建一個函數,select語句如何實現這一點?我不能爲我的生活提出一個解決方案。

編輯:

使用MS SQL Sever的2008

Management Studio中10.0.1600.22

回答

3

如果您使用的是支持FULL OUTER JOIN語法數據庫,那麼你可以使用:

select 
    coalesce(ot.record_id, nt.record_id) record_id, 
    ot.name OT_Name, 
    nt.name NT_name, 
    coalesce(ot.sequence_num, nt.sequence_num) Sequence_num 
from old_table ot 
full outer join new_table nt 
    on ot.record_id = nt.record_id 
    and ot.sequence_num = nt.sequence_num 

SQL Fiddle with Demo

+0

這是接近的,但我不能改變在NEW_TABLE – Proxy404 2013-02-21 21:46:51

+0

@ Proxy404名稱的順序看我的編輯,我改變了加入使用'record_id'和'sequence_num'現在看起來是正確的。 – Taryn 2013-02-21 21:49:03

+0

這在SQL小提琴中完美工作。但它似乎只顯示在我的環境中具有匹配Sequence_nums的行。 (即它只顯示sequence_num爲0,1和2的行) – Proxy404 2013-02-21 22:21:26

2

以下將在任何數據庫中工作。它不依賴於full outer join

select record_id, 
     MAX(case when which = 'ot' then name end) as ot_name, 
     MAX(case when which = 'nt' then name end) as nt_name, 
     sequence_num 
from ((select record_id, name, sequence_num, 'ot' as which 
     from ot 
    ) union all 
     (select record_id, name, sequence_num, 'nt' as which 
     from nt 
    ) 
    ) t 
group by record_id, sequence_num