0

我希望比较两组数据并显示两组的完整并集,并添加列以显示行是否出现在集合 1、集合 2 或两者中。我正在使用 T-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 中完成吗?我会满足于让添加的列只是输出为 A、B 或两者的 1 列。

4

2 回答 2

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。如果任一表中有重复项,该解决方案可以增加行。此解决方案将删除重复项,即使在表中也是如此,因此多行将缩小为一行。

于 2013-06-21T02:09:02.393 回答
1

您可以使用 FULL 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 小提琴

您还可以将最后一部分合并到一个字段中:

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
于 2013-06-21T02:00:40.183 回答