Ввод левой таблицы:

Правая таблица ввода :

Окончательный результат:

Цель состоит в том, чтобы создать столбец «new_value» в конечном выводе на основе вложенных условий ниже:
Код: Выделить всё
CASE WHEN value IS NULL
AND left_table.country IN (SELECT DISTINCT country from right_table)
THEN CASE WHEN left_class = 'class1' THEN
CASE WHEN (
SELECT value
from right_table n
WHERE (n.right_class = 'class2')
AND n.country= right_table.country
AND n.year = left_table.year) IS NOT NULL
THEN (
SELECT SUM(value)*2
from right_table n
WHERE (n.right_class = 'class1' OR n.right_class = 'class2')
AND n.country= left_table.country
AND n.year = left_table.year)
ELSE (
SELECT SUM(value)*2
from right_table n
WHERE (n.right_class = 'class1' OR n.right_class = 'class3')
AND n.country= left_table.country
AND n.year = left_table.year)
END
ELSE NULL END
ELSE value END AS new_value
Подробнее здесь: https://stackoverflow.com/questions/790 ... conditions