首页 > 解决方案 > 基于分区添加列 - Oracle

问题描述

桌子:

Col1       Col2         Col3
43         1234         abc
42         1234         abc
41         1234         abc
35         1234         abc
34         5678         def

目标是根据以下内容创建一个Col41 或 0 的新列:

在每个分区内使用 with Col2 and Col3
要么

  1. 如果 Col1-1 不存在(或)
  2. 如果 Col1-1(和)Col1-2 两个值都存在于表中,
    则 Col4 为 1,否则为 0。

输出表:

 Col1            Col2         Col3        Col4
 43              1234         abc         1
 42              1234         abc         0
 41              1234         abc         1
 35              1234         abc         1
 34              5678         def         1

标签: sqloracle

解决方案


如果我遵循您描述的逻辑:

select t.*,
       (case when lag(col1) over (partition by col2, col3 order by col1) <> col1 - 1
             then 1
             when lag(col1) over (partition by col2, col3 order by col1) is null
             then 1
             when lag(col1, 2) over (partition by col2, col3 order by col1) = col1 - 2
             then 1
             else 0
        end) as col4
from t;

是一个 db<>fiddle。


推荐阅读