我有一个用于获取FX值的子查询,该查询本身用作实例化视图的一部分。
当前,我的子查询代码如下:
fx_rate AS (
SELECT year::INT AS date,
CASE WHEN r.counter_currency_code = 'EUR' THEN (SELECT g.country_iso)
WHEN r.counter_currency_code = 'XOF' THEN (SELECT g.country_iso)
ELSE (SELECT reporter_iso FROM countries_view c where c.reporter = r.counter_currency LIMIT 1)
END AS country_iso,
yearlyaverage AS fx_rate
FROM currency_rates_view r left join currency_groups g on r.counter_currency_code = g.currency_group_code
)
然后在所有国家/地区的外部联接中将其用于实体化视图。
我没有美国(我认为是其中一个国家)的货币数据,所以我只希望每年返回1的值。
有没有一种方法可以添加此内容,以便在执行“选择”时看起来像这样:
date | country_iso | fx_rate
------+---------+---------------------
2018 | CMR | 556.971455938697
2016 | USA | 1
2017 | USA | 1
2018 | USA | 1
etc.
答案 0 :(得分:1)
您可以使用union all
和generate_series()
吗?
SELECT year::INT AS date,
(CASE WHEN r.counter_currency_code = 'EUR' THEN (SELECT g.country_iso)
WHEN r.counter_currency_code = 'XOF' THEN (SELECT g.country_iso)
ELSE (SELECT reporter_iso FROM countries_view c where c.reporter = r.counter_currency LIMIT 1)
END) AS country_iso,
yearlyaverage AS fx_rate
FROM currency_rates_view r LEFT JOIN
currency_groups g
ON r.counter_currency_code = g.currency_group_code
UNION ALL
SELECT gs.year, 'USA' as country_iso, 1
FROM generate_series(2000, 2018, 1) gs(year)