Я пытаюсь оптимизировать мой код.Решение, описанное ниже, работает нормально, но я уверен, что есть лучшие способы сделать это.Есть ли у вас какие-либо рекомендации?
У меня есть одна таблица с бизнес-контрактами и некоторыми характерными атрибутами:
table_contracts
contract_number attribute_1 attribute_2 attribute_3
123 a e t
456 a f s
789 b g s
И вторая таблица, которая отображает каждый контракт в определенную группу.Эти группы имеют разные приоритеты (большее число => более высокий приоритет).Если столбец атрибута является пустым, это означает, что он не требуется (=> m3 является отображением перехвата всех)
table_mappings
map_number priority attribute_1 attribute_2 attribute_3
m1 5 a e t
m2 4 a
m3 3
В результате мне нужен номер контракта и соответствующий номер карты с наивысшим приоритетом.
Вот как я это сделал, это работает, но кто-нибудь знает, как это оптимизировать?
with
first_selection as
(
select
table_contracts.contract_number
,table_mappings.priority
,row_number() over(partition by table_contracts.contract_number order by table_mappings.priority desc)
from table_contracts
left join table_mappings
on (table_contracts.attribute_1 = table_mappings.attribute_1 or table_mappings.attribute_1 is null)
and (table_contracts.attribute_2 = table_mappings.attribute_2 or table_mappings.attribute_2 is null)
and (table_contracts.attribute_3 = table_mappings.attribute_3 or table_mappings.attribute_3 is null)
),
second_selection as
(
select
table_contracts.contract_number
,table_mappings.priority
,table_mappings.map_number
from table_contracts
left join table_mappings
on (table_contracts.attribute_1 = table_mappings.attribute_1 or table_mappings.attribute_1 is null)
and (table_contracts.attribute_2 = table_mappings.attribute_2 or table_mappings.attribute_2 is null)
and (table_contracts.attribute_3 = table_mappings.attribute_3 or table_mappings.attribute_3 is null)
)
select
first_selection.contract_number
,second_selection.map_number
from first_selection
join second_selection
on first_selection.contract_number = second_selection.contract_number and first_selection.priority = second_selection.priority
where first_selection.rn = 1
Вывод этого кода будет:
Results
contract_number map_number
123 m1
456 m2
789 m3