【发布时间】:2016-05-01 23:04:31
【问题描述】:
我正在尝试在 Oracle 中优先选择。找到SQL Select with Priority 类似,但我的优先级表结构不同(我无法控制表结构)。样本数据为:
item_table:
item_id | part_id | priority_id | snapshot
1 | 1 | 1 | 42
1 | 2 | 1 | 42
part_table:
part_id | priority_type | value | snapshot
1 | P | 10 | 42
1 | F | 20 | 42
2 | P | 10 | 42
2 | D | 50 | 42
priority_table
priority_id | priority_1 | priority_2 | priority_3
1 | D | P | F
2 | P | B | C
零件表只有优先级类型,没有ID。 item 表只有部件的优先级 id,没有类型。每个项目的快照都是唯一的,因此如果我知道它是 part_id 和 item_table 中的快照,我可以在 part_table 中找到特定部分。
我希望得到的输出类似于:
item_id | part_id | value
1 | 1 | 10
1 | 2 | 50
选择项目 ID、零件 ID、值
其中 value 来自行 where priority_type = priority_1 where priority_id from item table = priority_id from priority_table(由 part_id 连接的 item 和 part 表)如果在 part_table 中存在这样的 priority_type 条目。
如果在零件表中找不到priority_1 的条目,则选择priority_type = priority_2 等的值
对于给定的部分/priority_id,可能不存在priority_1条目,在这种情况下,如果存在,则应采用priority_2,如果不存在,则采用priority_3(总共有4个,如果这样更容易的话)
希望获取所有项目、所述项目的所有部分以及每个部分的“最高优先级”值的列表。我意识到可以更好地创建优先级表,但这不在我的控制范围内。
到目前为止,我已经想出了一个嵌套案例,类似于:
select i.item_id,
i.part_id,
p.value
from item_table i
join part_table p
on i.part_id = p.part_id
where p.priority_type = (case when
(select priority_1
from priority_table
where priority_id =
(select priority_id
from part_table
where part_id = p.part_id
and snapshot = p.snapshot)) = priority_type
then priority_type
else...(inner case for priority_2, which has an else containing an inner case for priority_3, which has an else containing an inner case for priority_4)
我意识到这远非最佳解决方案,但 SQL 不是我的主要内容,而且这个特定优先级表的结构也不是(应该)正常构造它的方式。我觉得我错过了一些非常简单的东西,但无法弄清楚。
【问题讨论】:
-
您是否尝试过 Oracle 中的“排序”分析功能。他们可以根据列值对其进行排名。它使这些查询更容易。也可以试试 with 子句,它使查询更简单、更易读。例如,您的内部查询可以进入 with 子句,并且可以像视图一样连接到外部查询。
标签: sql oracle optimization