【问题标题】:Mssql union two tables based on column valuemssql根据列值联合两张表
【发布时间】:2014-08-20 15:55:53
【问题描述】:

我必须将两个都携带客户数据的表格(tab_a 和 tab_b)。这两个表有一些共同的记录,或者更好的是,共同的客户。问题是它们由不同的客户代码标识,并且同一客户的名称可能因一张表而异。他们唯一的共同点是增值税号。 我需要的是一个记录集,其中包含两个表中的客户,但没有重复。

我尝试了一个常规的 UNION,但问题是如果客户的名字写的从一个表到另一个表略有不同,我会得到一个重复。

我简短我需要

的结果
SELECT t1.vatnumber FROM tab_a AS t1 UNION t2.vatnumber FROM tab_b AS t2

但是加上客户的名字和他的客户代码(取自 tab_a 或者如果不存在于 tab_a 中的 tab_b)

非常感谢任何帮助。

问候

【问题讨论】:

  • 你用的是什么数据库

标签: sql union


【解决方案1】:

distinct 不会让您轻易得到想要的东西。更好的方法可能是 union all 与聚合。以下返回你想要的——但没有优先级。也就是说,如果两个表中都存在名称或代码,则返回任意一个:

select vatnumber, max(name) as name, max(code) as code
from ((select a.vatnumber, a.name, a.code
       from tab_a
      ) union all
      (select b.vatnumber, b.name, b.code
       from tab_b
      )
     ) ab
group by vatnumber;

如果你想要优先级,那就有点麻烦了。这是一种方法:

select vatnumber,
       coalesce(max(case when which = 'a' then name end), max(name)) as name,
       coalesce(max(case when which = 'a' then code end), max(code)) as code
from ((select a.vatnumber, a.name, a.code, 'a' as which
       from tab_a
      ) union all
      (select b.vatnumber, b.name, b.code, 'b' as which
       from tab_b
      )
     ) ab
group by vatnumber;

【讨论】:

  • 太棒了!谢谢戈登!
【解决方案2】:

不要使用 UNION,使用 FULL OUTER JOIN 会更简单:

SELECT 
ISNULL(a.vatnumber, b.vatnumber) vatnumber, 
ISNULL(a.name, b.name) name,
...
FROM tab_a a FULL JOIN tab_b b ON a.vatnumber = b.vatnumber 

语法取决于您使用的数据库。例如这个例子对于 MSSQL 应该没问题。

【讨论】:

    猜你喜欢
    • 2017-05-28
    • 1970-01-01
    • 1970-01-01
    • 2013-09-07
    • 2014-04-12
    • 1970-01-01
    • 1970-01-01
    • 2013-06-07
    • 2021-09-17
    相关资源
    最近更新 更多