|
-
update first 3 rows from each deptno
Hi All,
Consider EMP table. I need to update sal = sal+100 of first 3 employee from each DEPTNO of order by deptno, ename. I mean update should perform after order by deptno, ename of first 3 rows. see below.
Before Update
=============
DEPTNO ENAME SAL
--------- ---------- ---------
20 SMITH 800
30 ALLEN 1600
30 WARD 1250
20 JONES 2975
30 MARTIN 1250
30 BLAKE 2850
10 CLARK 2450
20 SCOTT 3000
10 KING 5000
30 TURNER 1500
20 ADAMS 1100
30 JAMES 950
20 FORD 3000
10 MILLER 1300
After Update
============
DEPTNO ENAME SAL
--------- ---------- ---------
10 CLARK 2450+100
10 KING 5000+100
10 MILLER 1300+100
20 ADAMS 1100+100
20 FORD 3000+100
20 JONES 2975+100
20 SCOTT 3000
20 SMITH 800
30 ALLEN 1600+100
30 BLAKE 2850+100
30 JAMES 950+100
30 MARTIN 1250
30 TURNER 1500
30 WARD 1250
Thanks in advance.
-
You can achieve that using rownum pseudo column.
First use cursor/loop on the depts, and foreach dept, update sal= sal + 100 where rownum <= 3.
PLSQL should be used of course (loops, explicit cursors).
Oracle Certified Associate.
DBA & Programming.
-
P.S: makes sure you order the results properly after recieving the dept list, otherwise the rownum will be ineffective.
Oracle Certified Associate.
DBA & Programming.
-
PHP Code:
update emp e
set e.sal = e.sal+100
where e.empno in (select s.empno
from (select e2.empno
, row_number() over (partition by e2.deptno order by e2.ename) as rownumber
from emp e2
) s
where s.rownumber <=3
)
-
Hi Akkerend,
Thanks it work perfect!, thanks for your time to resolve this problem.
-
Hi Akkerend,
Is there any way without using "row_number() over (partition by " we can resolve this, the reason I have to use this query in Developer 2000 Beforereport and can't compile however it works on sql*plus session.
Thanks.
-
It ought to run OK as dynamic SQL.
-
"It ought to run OK as dynamic SQL."
Not sure what is your mean.
Thanks.
-
Use DBMS_SQL or "execute immediate" syntax to execute the statement
-
In 8i some new SQL features, like ROW_NUMBER and other analytical functions, don't work in PL/SQL.
There are two workarounds:
1. Dynamic SQL, with EXECUTE IMMEDIATE:
PHP Code:
create procedure...
...
begin
...
execute immediate 'update emp set ...';
...
end;
/
2. create a view and use the view in PL/SQL:
PHP Code:
create or replace view emp_rownumber
as
select e.empno
, row_number() over (partition by e.deptno order by e.ename) as rownumber
from emp e;
create procedure...
...
begin
...
update emp e
set e.sal = e.sal+100
where e.empno in (select r.empno
from emp_rownumber r
where r.rownumber <=3
);
...
end;
/
Last edited by akkerend; 09-07-2004 at 04:36 PM.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|