【发布时间】:2018-06-11 22:31:04
【问题描述】:
我正在尝试优化我的代码。下面描述的解决方案工作正常,但我很确定有更好的方法来做到这一点。你有什么建议吗?
我有一张包含商业合同和一些特征属性的表格:
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
因此,我需要具有最高优先级的 contract_number 和相应的 map_number。
我就是这样做的,它可以工作,但有人知道如何优化它吗?
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
【问题讨论】:
-
请为上述输入添加示例输出,以便更好地理解问题。
-
@vCillusion:上面的帖子已编辑!
-
您使用的是哪个 Oracle 版本?
标签: sql oracle query-performance