I need help with writing more optimized SQL query when there is no logical connection between tables. I wrote some subqueries but I'm not satisfied with it because I'm repeating almost the same subquery twice.
The scheme goes like this:
create table rate (
rate_date date,
value decimal(10,2),
multiplier integer,
name varchar(3)
);
create table amount (
amount decimal(10,2),
amount_year date,
rate_name varchar(3)
);
I want every amount in AMOUNT
table to be calculated with multiplier and rate value from RATE
table like this amount / multiplier * rate
. Common things for both tables are name (some code identifier) and date. Those should be used to get the data together. Only the newest rates for amount_year are taken into account.
You can check this fiddle if you're willing to help. That's my try.
select am.amount /
(
select ra.multiplier
from rate ra
where ra.rate_date = (select max(rate_date)
from rate
where year(rate_date) = year(am.amount_year) and name = am.rate_name)
and ra.name = am.rate_name
) * (
select ra.value
from rate ra
where ra.rate_date = (select max(rate_date)
from rate
where year(rate_date) = year(am.amount_year) and name = am.rate_name)
and ra.name = am.rate_name
) as calculated_amount
from amount am;