0

我有两张桌子:

financials_standalone ('fin_id', 'attr_id', 'year', 'value');
financials_consolidated ('fin_id', 'attr_id', 'year', 'value');

('fin_id', 'attr_id', 'year') is the unique key

除了financials_standalone 之外,financials_consolidated 表还有数据。

例如:

financials_standalone
| fin_id |   attr_id | year | value   |
---------------------------------------
|  fin01 | pe        | 2016 |   33.23 |
|  fin02 | pe        | 2016 |   12.52 |

financials_consolidated
| fin_id |   attr_id | year | value   |
---------------------------------------
|  fin02 | pe        | 2016 |   20.41 |

现在我想将这两个表合并为一个视图:- 如果该行存在于合并中,则选择该行,否则从 Financials_standalone 表中选择该行。

所以最终的视图输出应该是这样的

financials_data_view
| fin_id |   attr_id | year | value   |
---------------------------------------
|  fin01 | pe        | 2016 |   33.23 |
|  fin02 | pe        | 2016 |   20.41 |

我无法通过 case-when 或 left external join 找到解决方案。如何获得此视图输出?

4

1 回答 1

1

左连接financials_standalone以在所有情况下financials_consolidated获取值financials_consolidated,并使用 coalesce() 函数从 2 个表中返回第一个非空值。然后进行联合以获取这些记录,financials_consolidated以从该表中获取另一个表中不存在的记录。如果情况并非如此,那么您就不需要工会。

select fs.fin_id, fs.attr_id, fs.year, coalesce(fc.value, fs.value) as val
from `financials_standalone` fs
left join `financials_consolidated` fc
    on fs.fin_id=fc.fin_id
    and fs.attr_id=fc.attr_id
    and fs.year=fc.year
union
select fc.fin_id, fc.attr_id, fc.year, fc.value
from `financials_consolidated` fc
left join `financials_standalone` fs
    on fs.fin_id=fc.fin_id
    and fs.attr_id=fc.attr_id
    and fs.year=fc.year
where fs.fin_id is null
于 2016-10-31T10:35:00.837 回答