0

我的源数据


ename   Age
BAL          N
BAL          Y
BAL          Y
YUV          N
YUV          Y
NAR          N

逻辑


if ( (ename <> Previous_Ename or Previous_AGE='N') then AGE = as is Else AGE='Y'

能否请您告诉我如何使用 Oracle funcaiton 进行编码?我尝试过,但在所有情况下它都没有显示所需的结果集。

我用了


create or replace function () RETURN
    VARCHAR2
IS
      previous_name VARCHAR2 (9) := 'DUMMY';
      previous_age  VARCHAR2 (9) := 'Z';
    BEGIN
    For cur_rec in (select ename, age from tablename order by ename) LOOP
    if ( cur_rec.ename <> previous_ename or previous_age ='N')
        then return cur_rec.age;   /** it is populating the result set with only "N"***/
            else return 'Y';
        end if;
                previous_ename :=ename;   /*** not sure whether this assignment is correct- im trying to assignt current value as previous value for next row reference.****/
                    previous_age :=age;      /*** not sure whether this assignment is correct****/
        END LOOP;
    END

结果我得到:-实际上结果应该与此数据场景的源相同


ename   Age
BAL           N
BAL           N
BAL           N
YUV           N
YUV           N
NAR           N
4

1 回答 1

1

我仍然不明白你想要在这里实现什么(完全)......或者为什么

问题是你试图在一个函数中做到这一点,但你几乎立即返回了一些东西。根据您的订单逻辑(在评论中),第一个值将始终是N因为这是 ORDER BY 中的第一个值。对于表中的每条记录,这都是正确的。

改用 MERGE 语句:

merge into tmp n
using ( select rowid as rid
             , ename
             , age
             , lag(age) over ( partition by ename order by age ) as lag_age
          from tmp
               ) o
   on ( n.rowid = o.rid )
 when matched then
      update
         set n.age = case when lag_age is null then age
                          when lag_age = 'N' then age
                          else 'Y' 
                     end
       ;

SQL小提琴

于 2013-08-25T21:57:06.597 回答