2013-06-21 60 views
0

我希望比較兩組數據並顯示兩個集合的完全並集,並添加列以顯示一行出現在集合1,集合2還是兩者中。我正在使用T-SQL比較SQL表格:顯示完整集合和任何差異

Table A 
|[ID] | [Movie] | [Year] | 
|-----|---------|--------| 
| 1 | Movie1 | Year1 | 
| 2 | Movie2 | Year2 | 
| 3 | Movie3 | Year3 | 

Table B 
|[ID] | [Movie] | [Year] | 
|-----|---------|--------| 
| 2 | Movie2 | Year2 | 
| 3 | Movie3 | Year3 | 
| 4 | Movie4 | Year4 | 


Desired Result: 
|[ID] | [Movie] | [Year] | [In Set A?] | [In Set B?] | 
|-----|---------|--------|-------------|-------------| 
| 1 | Movie1 | Year1 | Yes  |  No  | 
| 2 | Movie2 | Year2 | Yes  |  Yes  | 
| 3 | Movie3 | Year3 | Yes  |  Yes  | 
| 4 | Movie4 | Year4 | No  |  Yes  | 

這是可以在SQL中完成的嗎?我希望添加的列只有1列,輸出是A,B或兩者。

+0

也有像兩個表中有不同數據的相同ID的邊緣情況,等等。 –

+0

你正在使用什麼數據庫系統? –

回答

1

您可以使用完整的JOIN和COALESCE,這是假設你可以加入對ID:

SELECT COALESCE(a.ID,b.ID)as ID 
    , COALESCE(a.Movie,b.Movie) as Movie 
    , COALESCE(a.Year,b.Year) as Year 
    , CASE WHEN a.ID IS NULL THEN 'NO' ELSE 'YES' END as InSetA 
    , CASE WHEN b.ID IS NULL THEN 'NO' ELSE 'YES' END as InSetB 
FROM TableA a 
FULL JOIN TableB b 
ON a.ID = b.ID 

演示:SQL Fiddle

你也可以合併的最後部分爲一個字段:

SELECT COALESCE(a.ID,b.ID)as ID 
    , COALESCE(a.Movie,b.Movie) as Movie 
    , COALESCE(a.Year,b.Year) as Year 
    , CASE WHEN a.ID IS NULL THEN 'In B Only' 
      WHEN b.ID IS NULL THEN 'In A Only' 
      ELSE 'In Both' 
     END as InTable  
FROM TableA a 
FULL JOIN TableB b 
ON a.ID = b.ID 
1

您可以用union all做到這一點:

select id, movie, year, 
     (case when max(inA) = 1 then 'Yes' else 'No' end) as inA, 
     (case when max(inB) = 1 then 'Yes' else 'No' end) as inB 
from (select id, movie, year, 1 as InA, 0 as InB 
     from tableA 
     union all 
     select id, movie, year, 0, 1 
     from tableB 
    ) t 
group by id, movie, year 

這與full outer join解決方案略有不同。如果兩個表中有重複,那麼該解決方案可以將行數相乘。此解決方案將刪除重複項,即使在一個表中,也會將多行縮小爲一行。

+0

我喜歡這種方式,我的編輯是出現在建議中還是隻是被打到位? –

+0

這很好,謝謝。我喜歡互聯網......它只是幫助人們的人! – user2507320