首页 > 解决方案 > 根据列 oracle 中的数据定义组

问题描述

我在 col 1 中有一个带有 oracle 序列的表,我需要根据 col 2 中的值进行分组。下面是带有数据的示例表。数据库版本 = Oracle 12.1

分组的条件是 col2 应该有 50,或者如果它有 30,那么下一个 50 应该属于同一组。不能一个人有30个,后面会有50个

我写了以下内容,但没有得到预期的结果

SELECT col1,col2,count(CASE WHEN col2 in (30,50) THEN 1 END)OVER(ORDER BY col1) from table.

最后我需要最高组,这是可行的。

Col1  Col2   Expected output Grp
----- -----  -------------------
1      3
2      50        1
3      10
4      2
5      30        2
6      12
7      50        2
8      14
9      50        3
10     50        4

标签: sqloracleoracle12c

解决方案


嗯。. . 我认为逻辑是这样的:

select t.*,
       sum(case when col2 = 50 and
                     (prev_30 is null or prev_30 < prev_50)
                then 1 else 0
           end) over (order by col1) as grp
from (select t.*,
             lag(case when col2 = 50 then col1 end ignore nulls) over (order by col1) as prev_50,
             lag(case when col2 = 30 then col1 end ignore nulls) over (order by col1) as prev_30
      from t
     ) t;

我们的想法是获取col1“50”和“30”的先前值,我们可以使用ignore nulls 选项lag()(或使用累积条件最大值)来做到这一点。

那么定义组的逻辑是开始每个组的“50”的累积总和。


推荐阅读