我有两个表来存储我系统中的汇率。第一个 agent_rate 如下。
ID Currency Rate
=======================
3 GBP 0.65
4 EUR 0.70
5 JPY 57.4
第二个表 exchange_rate 如下。
ID Currency Rate
=======================
1 USD 1
2 ZMK 200
3 GBP 0.5
4 EUR 0.75
5 JPY 60.4
6 CHF 0.9
我想选择第一个表 agent_rate 中的所有行,然后从 exchange_rate 表中添加ID的所有缺失值。我想在单个列上使用带有distinct的union语句,但我没有。我目前的解决方案如下(visual studio)
结果表是(应该)如下:
ID Currency Rate
=======================
1 USD 1
2 ZMK 200
3 GBP 0.65
4 EUR 0.70
5 JPY 57.4
6 CHF 0.9
在Sql中有更好的方法吗?
答案 0 :(得分:1)
您可以加入该表并首先选择代理值(如果存在),否则选择交换表中的值
select coalesce(a.id, e.id) as id,
coalesce(a.currency, e.currency) as currency,
coalesce(a.rate, e.rate) as rate
from exchange_rate e
left agent_rate a on a.id = e.id
coalesce
返回提供的列表中的第一个非空值。