SQL优先级选择

时间:2016-02-20 16:38:45

标签: sql oracle optimization

我正试图在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,而不是类型。快照对于每个项目都是唯一的,所以如果我从item_table知道它的part_id和快照,我可以在part_table中找到特定的部分。

我希望获得的输出类似于:

item_id | part_id | value
      1 |       1 |    10
      1 |       2 |    50

选择项目ID,部件ID,值
其中value来自priority_type = priority_1的行,其中priority_id来自item table = priority_id来自priority_table(项目和部分表由part_id连接),如果在part_table中存在priority_type的这样的条目。
如果在part表中找不到priority_1的条目,则选择priority_type = priority_2等的值

对于给定的部分/ priority_id,priority_1条目可能不存在,在这种情况下,如果存在,则应该采用priority_2,如果不存在,则优先级为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不是我的主要内容,而这个特定优先级表的结构并不是人们应该(应该)正常构建它的方式。我觉得我错过了一些非常简单的事情,但无法理解。

1 个答案:

答案 0 :(得分:5)

这是一种方法

SELECT it.item_id,
       it.part_id,
       COALESCE(p1.value, p2.value, p3.value) AS value
FROM   item_table it
       INNER JOIN priority_table pt
               ON it.priority_id = pt.priority_id
       LEFT JOIN part_table p1
              ON p1.priority_type = pt.priority_1
                 AND p1.part_id = it.part_id
       LEFT JOIN part_table p2
              ON p2.priority_type = pt.priority_2
                 AND p2.part_id = it.part_id
       LEFT JOIN part_table p3
              ON p3.priority_type = pt.priority_3
                 AND p3.part_id = it.part_id