如何选择下一个最高ID?

时间:2016-04-13 14:14:25

标签: oracle plsql

我有一个程序来计算实现结果所需的时间。因此,例如,在案例具有代码“CB”的情况下,过程应该在表EVENTS中查找下一次应用一组结果代码之一并使用DATE_CREATED值来设置CB_DATE的值。案例可能有多个代码,但我只对CB代码后的第一次使用感兴趣:示例表如下:

ID   CASE_ID DATE_CREATED    DATE_MODIFIED    OUTCOME_CODE  CB_DATE    
1     01      01/04/1970      01/04/1970      CASE_START
2     01      01/04/1970      02/04/1970      CB
3     01      01/04/1970      03/04/1970      PPLF
4     02      01/04/1970      02/04/1970      TEST
4     01      01/04/1970      04/04/1970      SACM
5     01      01/04/1970      05/04/1970      TEST         05/04/1970
6     01      01/04/1970      06/04/1970      OUTC             

所以我想为代码所在的'CB'之后的下一个条目返回DATE_MODIFIED('OUTC','TEST'),在上面的示例中,它将是'TEST'的第二个实例作为第一个实例适用于不同的CASE_ID。

目前它正在将该过程应用于结果代码集的每个实例,如上例所示,TEST和OUTC的实例都获得了CB_DATE值,但我只是希望TEST具有CASE_ID与'的CASE_ID匹配的值CB的结果。

目前的代码是:     更新活动e     设置CB_DATE = DATE_MODIFIED     其中OUTCOME_CODE('TEST','OUTC'....)

我以为我可以使用

  update   EVENTS e
  set      CB_DATE=DATE_MODIFIED
  WHERE    OUTCOME_CODE in ('TEST','OUTC'....)
  AND      ID > (
    select ID
    from   EVENTS x
    where  x.OUTCOME_CODE = 'CB'
    and    x.CASE_ID=e.CASE_ID);

2 个答案:

答案 0 :(得分:1)

可能不是最佳但是:

UPDATE tt e
   SET CB_DATE = DATE_MODIFIED
 WHERE OUTCOME_CODE IN ('TEST', 'OUTC')
   AND id > (SELECT MAX (id)
               FROM tt x
              WHERE x.id < e.id AND x.outcome_code = 'CB' AND x.case_id = e.case_id)
   AND NOT EXISTS
          (SELECT 1
             FROM tt y
            WHERE y.id < e.id
              AND y.OUTCOME_CODE IN ('TEST', 'OUTC')
              AND y.case_id = e.case_id
              AND y.id > (SELECT MAX (id)
                            FROM tt x
                           WHERE x.id < e.id AND x.outcome_code = 'CB' AND x.case_id = e.case_id))

其他方式是获得CB范围:

SELECT id, LEAD (id, 1, 99999999999999) OVER (PARTITION BY case_id ORDER BY id) next_id, case_id
  FROM tt
 WHERE outcome_code = 'CB'

获取具有最小ID的记录,其中代码为('TEST','OUTC')

UPDATE tt e
   SET CB_DATE = DATE_MODIFIED
 WHERE OUTCOME_CODE IN ('TEST', 'OUTC')
   AND (id, case_id) IN 
      (SELECT (SELECT MIN (id)
                FROM tt
               WHERE OUTCOME_CODE IN ('TEST', 'OUTC') AND id BETWEEN cbs.id AND cbs.next_id AND case_id = cbs.case_id) test_id,
             cbs.case_id
        FROM (SELECT id, LEAD (id, 1, 99999999999999) OVER (PARTITION BY case_id ORDER BY id) next_id, case_id
                FROM tt
               WHERE outcome_code = 'CB') cbs)

用事件改变tt。

答案 1 :(得分:0)

我一直在想这一切都错了。我需要寻找MIN(ID)而不是MAX(ID),而不是MAX(ID)。比当前的ID。

基本上我试图获得下一个最高ID,即满足其他条件的MIN(ID),即&gt;比CASE_ID匹配的现有ID和OUTCOME_CODE在相关组中的位置。

例如

   update   EVENTS e
   set      CB_DATE=DATE_MODIFIED
   WHERE    OUTCOME_CODE in ('TEST','OUTC'....)
   AND      MIN(ID) > (
        select ID
        from   EVENTS x
        where  x.OUTCOME_CODE = 'CB'
        and    x.CASE_ID=e.CASE_ID);