sql - 在 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
如何组合列,以便在一个表中找到时使用该列,反之亦然?
解决方案
您可以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
如果您的数据库支持using
to 子句joins
,则更简单:
select street, city,
coalesce(f.sales,0) - coalesce(b.purchases,0) as profit
from foo f
full join bar b using(street, city)
推荐阅读
- javascript - react, setState 并让组件重新渲染
- python - 如何在 jupyter notebook 上自动完成?
- dropzone.js - dropzone.js - 如何通过 api 触发文件上传?
- mongodb - findOneAndUpdate 中使用 $set 的聚合查询不更新文档
- json - 如何将bash变量添加到json文件?
- reactjs - 使用 React 钩子设置状态时引发跨源错误
- ruby-on-rails - 使用 rspec 测试具有产量的方法
- html - 选择元素后具有特定类的第一个兄弟
- numpy - 使用带有 numpy 或 scipy 数组的阶乘的混淆错误
- c# - 如果我设置版本,OData 元数据 url 请求将失败