首页 > 解决方案 > 在 SELECT 中使用 FULL JOIN,如何使用表中的某些列,但如果它为空,请使用另一个表中的列?

问题描述

我有两张桌子:

-- Foo --                 -- Bar --
Street | City | Sales     Street | City | Purchases
  X    |  A   |  2           Y   |  B   |   1
  Y    |  B   |  3           Z   |  C   |   4

我必须返回这个:

Street | City | Profit
  1    |  A   |   2
  2    |  B   |   2
  3    |  C   |  -4

我唯一想到的就是这个:

SELECT f.street, f.city, b.street, b.city, ISNULL(f.sales,0) - ISNULL(b.purchases,0) as Profit
FROM Foo f FULL JOIN Bar b
ON f.street = b.street AND f.city = b.city

我知道这不是我需要的,但得到了这个结果:

Street | City | Street | City | Profit
  1    |  A   |  NULL  | NULL |   2
  2    |  B   |   2    |  B   |   2
 NULL  | NULL |   3    |  C   |  -4

如何组合列,以便在一个表中找到时使用该列,反之亦然?

标签: sqlfull-outer-joinsql-null

解决方案


您可以coalesce()select子句中使用:

select coalesce(f.street, b.street), coalesce(f.city, b.city)
    coalesce(f.sales, 0) - coalesce(b.purchases, 0) as profit
from foo f 
full join bar b on f.street = b.street and f.city = b.city

如果您的数据库支持usingto 子句joins,则更简单:

select street, city, 
    coalesce(f.sales,0) - coalesce(b.purchases,0) as profit
from foo f 
full join bar b using(street, city)

推荐阅读