sql-计算基于另一列的一列

时间:2018-10-30 03:45:56

标签: sql oracle oracle12c

我有一个数据集

case_id    subcase_id
1      | 1-1
1      | 1-2
1      | 1-3
1      | 1-6
2      | 2-1
2      | 2-7

我想要以下输出。这个想法是计算与案例相对应的子案例的发生。

case_id  subcase_id
1      | 1-1          | 1
1      | 1-2          | 2
1      | 1-3          | 3
1      | 1-6          | 4
2      | 2-1          | 1
2      | 2-7          | 2

3 个答案:

答案 0 :(得分:3)

您可以尝试使用row_number()函数

select 
   caseid,
   subcase_id, 
   row_number() over(partition by caseid 
      order by 
      cast(SUBSTR(subcase_id, 1,INSTR(subcase_id, '-') -1) as number), 
      cast(SUBSTR(subcase_id, INSTR(subcase_id, '-') +1) as number)) as rn
from tablename

答案 1 :(得分:1)

您可以将count() over (partition by .. order by ..)子句用作:

    with t(case_id,subcase_id) as
    (   
     select 1,'1-1' from dual union all
     select 1,'1-2' from dual union all
     select 1,'1-3' from dual union all
     select 1,'1-6' from dual union all
     select 2,'2-1' from dual union all
     select 2,'2-7' from dual
    )
     select t.*,
            count(*) over (partition by case_id order by subcase_id)              
            as result
       from t;

    CASE_ID     SUBCASE_ID   RESULT
    -------     ----------   ------ 
       1            1-1        1
       1            1-2        2
       1            1-3        3
       1            1-6        4
       2            2-1        1
       2            2-7        2

,其中subcase_id经常更改并且对于所有值都是不同的,而case_id很少更改。

Rextester Demo

答案 2 :(得分:0)

这是一个查询,其行为应如您所愿。我们必须隔离subcase_id的两个数字部分,然后将它们转换为整数,以避免将此列作为文本排序。

SELECT
    case_id,
    subcase_id,
    ROW_NUMBER() OVER (PARTITION BY case_id
        ORDER BY TO_NUMBER(SUBSTR(subcase_id, 1, INSTR(subcase_id, '-') - 1)),
                 TO_NUMBER(SUBSTR(subcase_id, INSTR(subcase_id, '-') + 1))) rn
FROM yourTable
ORDER BY
    case_id,
    TO_NUMBER(SUBSTR(subcase_id, 1, INSTR(subcase_id, '-') - 1)),
    TO_NUMBER(SUBSTR(subcase_id, INSTR(subcase_id, '-') + 1));

Demo

subcase_id列同时视为文本和数字不是一个好主意。如果您确实需要长期在此列上进行排序,那么建议您将两个数字部分分解为单独的数字列。