2013-10-08 89 views
-1

我有2個表需要根據關鍵進行合併。在關鍵sql服務器上合併列

表-1

enter image description here

表-2

enter image description here

輸出:

enter image description here

查詢中使用:

select TB1.EMP_NUM , TB1.EMP_NAME , TB1.EMP_SALARY , TB2.EMP_AGE 
      from EMPLOYEE_MERGE_1 tb1 full outer join EMPLOYEE_MERGE_2 tb2 ON TB1.EMP_NUM = TB2.EMP_NUM 

預期輸出:

對於最後一個記錄,Emp_num,EMP_NAME,emp_salary應該從表1稀少,因爲我使用的是全外連接其使得空值。我可以添加null檢查到關鍵列(emp_num)和列表form_1(emp_name & emp_salary)並相應填充,但擔心,如果它包含實際的空值...

回答

0

這是怎麼回事?如果TB1中沒有匹配的行,這將爲您提供EMP_NUM和EMP_NAME的TB2值。

select COALESCE(TB1.EMP_NUM, TB2.EMP_NUM) AS EMP_NUM, 
    COALESCE(TB1.EMP_NAME, TB2.EMP_NAME) AS EMP_NAME, 
    TB1.EMP_SALARY, TB2.EMP_AGE 
from EMPLOYEE_MERGE_1 tb1 full outer join EMPLOYEE_MERGE_2 tb2 ON TB1.EMP_NUM = TB2.EMP_NUM 
+0

如果tb1.EMP_NUM和tb1.emp_name具有實際空值,那麼我不應該填充tb2.emp_num&tb2.emp_name – user1050619

+0

@ user1050619你什麼計劃在TB2中使用TB1中沒有匹配的EMP_NUM的行?如果這種情況不會發生,那麼你應該使用'LEFT OUTER JOIN'而不是'FULL OUTER JOIN'。否則,您至少要保留EMP_NUM的'COALESCE',然後可以在EMP_NAME中使用'CASE'語句來檢查'TB1.EMP_NUM IS NULL'。 –

0
select TB1.EMP_NUM , coalesce(TB1.EMP_NAME,TB2.EMP_NAME) , TB1.EMP_SALARY , TB2.EMP_AGE 
from EMPLOYEE_MERGE_1 tb1 full outer join EMPLOYEE_MERGE_2 tb2 
ON TB1.EMP_NUM = TB2.EMP_NUM 
0

試試這個:

DECLARE @list1 AS TABLE (Emp_Num INT, Emp_Name VARCHAR(100), Emp_Salary MONEY) 
DECLARE @list2 AS TABLE (Emp_Num INT, Emp_Name VARCHAR(100), Emp_Age INT) 

INSERT INTO @list1 
      SELECT 1, 'TOM', 5000 
UNION ALL SELECT 2, 'BRIAN', 6000 
UNION ALL SELECT 3, 'RAM', 8000 
UNION ALL SELECT 4, 'DINESH', 8000 


INSERT INTO @list2 
      SELECT 1, 'TOM', 20 
UNION ALL SELECT 2, 'BRIAN', 40 
UNION ALL SELECT 3, 'RAM', 60 
UNION ALL SELECT 5, 'SARATH', 90 

;WITH list AS (
SELECT Emp_Num, Emp_Name FROM @list1 
UNION 
SELECT Emp_Num, Emp_Name FROM @list2 
) 
SELECT L0.Emp_Num, L0.Emp_Name, EMP_SALARY = L1.Emp_Salary, EMP_AGE = L2.Emp_Age 
FROM list AS L0 
LEFT OUTER JOIN @list1 L1 ON L1.Emp_Num = L0.Emp_Num 
LEFT OUTER JOIN @list2 L2 ON L2.Emp_Num = L0.Emp_Num 



-- OUTPUT 
Emp_Num Emp_Name EMP_SALARY EMP_AGE 
1   TOM   5000.00  20 
2   BRIAN  6000.00  40 
3   RAM   8000.00  60 
4   DINESH  8000.00  NULL 
5   SARATH  NULL  90