2013-07-25 59 views
0
選擇不同的值

因此,這裏是我的設置我有2臺舊與新的下面(簡化)架構SQL從多個表

Old 
[ManName] 
[ManNumber] 

New 
[Manager_Name] 
[Manager_Number] 

我期待手藝返回以下,但在SQL查詢4列1個查詢,而不是2項的查詢與2列,每列

select distinct manname, mannumber from OLD 
select distinct Manager_Name, Manager_Number from NEW 

所以我理想中的結果集將有4列:

ManName ManNumber Manager_Name Manager Number 

謝謝!

+0

你能舉一個表格數據和所需輸出的例子嗎?另外,哪個RDBMS? SQL Server? –

回答

1

你試圖連接語句:

select distinct * 
from old a join new b on a.ManName = b. Manager_Name and a. ManNumber = b. Manager_Number 
+0

非常感謝!我的解決方案中幾乎全部都是這樣,但我從未想過要加入這兩個列。 –

+1

@BobFishel這將顯示錶格之間匹配的所有管理者,但沒有那些不匹配。可能是你想要的,但不是你問的東西:) –

+0

是的我把它切換到一個完整的外部連接:) –

1

使用幾乎任何關係型數據庫MySQL的以外,你可以用熱膨脹係數和ROW_NUMBER()做到這一點;

WITH cteOld AS (
    SELECT DISTINCT ManName, ManNumber, 
     ROW_NUMBER() OVER (ORDER BY ManNumber) rn FROM Old 
), cteNew AS (
    SELECT DISTINCT Manager_Name, Manager_Number, 
     ROW_NUMBER() OVER (ORDER BY Manager_Number) rn FROM New 
) 
SELECT ManName, ManNumber, Manager_Name, Manager_Number 
FROM cteOld 
FULL OUTER JOIN cteNew 
    ON cteOld.rn=cteNew.rn 

An SQLfiddle to test with

另一種更容易的方法就是簡單地使用UNION;

SELECT ManName, ManNumber, 0 isNew FROM Old 
UNION 
SELECT Manager_Name, Manager_Number, 1 FROM New 

Another SQLfiddle