繁体   English   中英

选择除一列之外的UNION

[英]select UNION except one column

我有个问题:

我想使用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'

这是另一种方法:

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

在这里演示

也许:

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  

在这里演示

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行。

你可以试试这个:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM