I am having the following issue. I have a table like the following that holds all the exchange rates per day for all currencies (as base currency is Euro):
id | rates_values | rate_date |
---|---|---|
1 | {"AED":2.835349,"AFN":67.743417,… | 1-1-2022 |
2 | {"AED":2.485349,"AFN":66.843814, | 2-2-2022 |
The column rates_values is in JSON. I have another table which is like the following one:
currency | cost | date_of_sale |
---|---|---|
AED | 150 | 1-1-2022 |
AFN | 250 | 2-2-2022 |
EUR | 56 | 2-2-2022 |
I join these 2 tables on date.
As next step, I want to extract the value that is referred on the currency column from the rates_values column but I don’t know how. A desirable result would be the below:
currency | extracted_values_for_each_sale |
---|---|
AED | 2.835349 |
AFN | 66.843814 |
EUR | 1 |
I can write a really long CASE…WHEN… statement and each time extract the matching value but that’s not the optimal solution.
2
Answers
This can be simply achieved by using the column as the JSON key when getting the appropriate rate:
(currency is the column from the second table in the question).
You may first normalize (or flatten) the exchange rates table like this (
exchange_rates
CTE is a mimic of the real table):and then join with it as you need.