Oracle SQL根据另一列中的条件查找顺序值

时间:2016-07-18 15:17:31

标签: oracle

我正在做一个项目来查找表中配对的左右部分的列表。该表包含一列唯一部件ID和一列左或右属性。

如果表格中有左右对,则左侧ID将在右侧之前显示一个唯一部件ID(ID 4将为左侧,ID 5将为右侧)。但是,每个左右对之间有许多唯一ID,没有一对。我试图编写一个查询来查找表中的所有左对和右对。

例如(当前ID和LR都是VARCHAR2)

ID  LR
1   L
2   R
5   R
9   R
22  R
34  L
35  R
38  L
91  L
92  R

我需要查询返回

ID  LR
1   L
2   R
34  L
35  R
91  L
92  R

我当前的思路是条件查询选择所有ID和LR当LR是R时ID-1存在且LR是L但是我不确定...任何帮助将不胜感激!谢谢。

2 个答案:

答案 0 :(得分:0)

with inputs ( id, lr ) as (
       select  1, 'L' from dual union all
       select  2, 'R' from dual union all
       select  5, 'R' from dual union all
       select  9, 'R' from dual union all
       select 22, 'R' from dual union all
       select 34, 'L' from dual union all
       select 35, 'R' from dual union all
       select 38, 'L' from dual union all
       select 91, 'L' from dual union all
       select 92, 'R' from dual
     ),
     prep ( id, lr, prev_lr, next_lr ) as (
       select id, lr, lag(lr) over (order by id), lead(lr) over (order by id)
       from   inputs
     )
select   id, lr
from     prep
where    (lr = 'L' and next_lr = 'R') or (lr = 'R' and prev_lr = 'L')
order by id
;


        ID L
---------- -
         1 L
         2 R
        34 L
        35 R
        91 L
        92 R

答案 1 :(得分:0)

设置操作是您可以这样做的一种方式。

(根据评论编辑重写查询 - 它现在处理varchar ID字段中的前导零)

WITH matches AS (
    SELECT to_number(ID) AS ID_integer
    FROM base_table
    WHERE LR = 'L'
    INTERSECT
    SELECT to_number(ID)-1
    FROM base_table
    WHERE LR = 'R'
)
SELECT bt.ID, bt.LR, m.ID_integer
FROM base_table bt, matches m
WHERE LR = 'L'
AND to_number(bt.ID) = m.ID_integer
UNION
SELECT bt.ID, bt.LR, m.ID_integer
FROM base_table bt, matches m
WHERE LR = 'R'
AND to_number(bt.ID)-1 = m.ID_integer
ORDER BY 3, 2;