我的源数据
ename Age
BAL N
BAL Y
BAL Y
YUV N
YUV Y
NAR N
逻辑
if((ename<> Previous_Ename或Previous_AGE ='N')则AGE = as 其他年龄='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
REsult im getting: - 实际上结果应该与此数据scenerio的Source相同
ename Age
BAL N
BAL N
BAL N
YUV N
YUV N
NAR N
答案 0 :(得分: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
;