问题
Suppose I have this table name_currency
in sqlite3.
name, currency, price
AA, SGD, 1
BB, USD, 2
CC, EUR, 3
I need to process the price in this manner.
if currency == "SGD", price = price*X
if currency == "USD", price = price*Y
if currency == "EUR", price = price*Z
The values of X
, Y
, Z
needs to be retrieved from another table currency_multiplier
. This is how currency_multiplier
looks like.
name, currency, multiplier
AA, SGD, 2 #value of X
BB, USD, 3 #value of Y
CC, EUR, 4 #value of Z
The output table will look like this after processing price
column;
name, currency, price
AA, SGD, 2
BB, USD, 6
CC, EUR, 12
Is it possible to do this entirely in sql? One solution I have in mind is to retrieve the values from name_currency
, then do the processing in a python function. However, I think it is more elegant to do it entirely in sql. Any hints on how to get started? Does SQL in sqlite3 support some form of function when processing becomes too complex?
回答1:
You may join the name_currency
table to the currency_multiplier
table:
SELECT
n.name,
n.currency,
c.multiplier * n.price AS price
FROM name_currency n
INNER JOIN currency_multiplier c
ON n.name = c.name;
Note that this runs the risk of dropping currencies from the report which appear in name_currency
but have no mapping in currency_multiplier
. But, in such a case, it is not clear how you would report anyway, because the multiplier/forex rate is not known.
来源:https://stackoverflow.com/questions/52866754/apply-processing-or-function-to-column-that-requires-retrieving-column-from-anot