select UNION 除了一列

select UNION except one column

我有一个问题:

我想使用 UNION 将两个 SQL 查询加入一个查询以避免重复,但我需要知道数据是来自第一个 select 查询还是第二个 select 查询.

示例数据:

 A TABLE                                                B TABLE
-----------------------------------------------------------------------------
01 JOHN                                                01 JOHN
02 JUAN                                                02 PETER
03 MARTIN                                              03 MARTIN

我有这样的东西:

Select A.code,A.name from A where some conditions
unión
Select B.code,B.name from B where diferent conditions

结果TABLE


    01 JOHN                                                
    02 JUAN  
    02 PETER
    03 MARTIN

这很好用,但现在如果我想知道数据是来自第一个查询还是第二个查询,我想是这样的:

Select A.code,A.name, 'A'   from A where some conditions
unión
Select B.code,B.name, 'B'   from B where diferent conditions

结果TABLE


    01 JOHN  'A'                                              
    01 JOHN  'B'
    02 JUAN  'A'
    02 PETER 'B'
    03 MARTIN 'A'
    03 MARTIN 'B'

但不要回避 "duplicates" 因为 'A' 与 'B' 不同,所以问题是,我能不能做点什么让他们不比较 [=41] =] 与 'B'?, 是另一种获得预期结果的方法吗?

编辑:

预期结果


    01 JOHN  'A'                                              
    02 JUAN  'A'
    02 PETER 'B'
    03 MARTIN 'A'

你可以试试这个:

Select A.code, A.name, 'A' col_name  from A where some conditions
UNION ALL
Select B.code, B.name, 'B'   from B where different conditions

Union 将删除重复项,而 Union All 则不会。

编辑:

SELECT *
FROM
(
SELECT DISTINCT A.code, A.name From A WHERE some conditions
UNION
SELECT DISTINCT B.code, B.name From B WHERE different conditions
) t
Select A.code, A.name, 'A' from A where some conditions
union
Select B.code, B.name, 'B' from B
where different conditions
  and not exists (select 1 from A
                  where some conditions
                    and A.code = B.code
                    and A.name = B.name)

像以前一样执行 UNION,但不要 return 已经从 A select 编辑的 B 行 return。

这是另一种方法:

SELECT code, name, MIN(SourceTable) AS SourceTable
FROM (
  SELECT code, name, 'A' AS SourceTable         
  FROM A

  UNION 

  SELECT code, name, 'B' AS SourceTable         
  FROM B) t
GROUP BY code, name 
ORDER BY code

Demo here

或者也许:

SELECT code, name, SourceTable
FROM (
  SELECT code, name, SourceTable,
         ROW_NUMBER() OVER (PARTITION BY code, name 
                            ORDER BY SourceTable) AS rn
  FROM (
    SELECT code, name, 'A' AS SourceTable         
    FROM A

    UNION ALL

    SELECT code, name, 'B' AS SourceTable         
    FROM B) t) AS x
WHERE x.rn = 1  

Demo here