选择除一列之外的UNION

时间:2015-09-21 09:39:56

标签: sql sql-server-2008 union

我有一个问题:

我想使用UNION将两个SQL查询连接到一个查询中以避免重复,但我需要知道数据是来自fisrt 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

结果表

    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

结果表

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

但是不要避免“重复”,因为'A'与'B'不同,所以问题是,我可以做一些事情,以便他们不将'A'与'B'进行比较吗?获得预期结果的另一种方法是什么?

编辑:

预期结果

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

3 个答案:

答案 0 :(得分:3)

这是另一种方法:

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

答案 1 :(得分:2)

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,但不要返回已从A select返回的B行。

答案 2 :(得分:1)

你可以试试这个:

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