— create
CREATE TABLE employee
(
emp_id INTEGER,
job_code TEXT,
cnt_check int
);
— insert
INSERT INTO employee(emp_id,job_code) VALUES (0001, 'JC001');
INSERT INTO employee(emp_id,job_code) VALUES (0001, 'JC001');
INSERT INTO employee(emp_id,job_code) VALUES (0002, 'JC002');
INSERT INTO employee(emp_id,job_code) VALUES (0002, 'JC002');
INSERT INTO employee(emp_id,job_code) VALUES (0003, 'JC003');
INSERT INTO employee(emp_id,job_code) VALUES (0004, 'JC004');
INSERT INTO employee(emp_id,job_code) VALUES (0004, 'JC004');
INSERT INTO employee(emp_id,job_code) VALUES (0004, 'JC004');
Expected Output:
emp_id job_code cnt_check
--------------------------------
0001 JC001 1
0001 JC001 2
0002 JC002 1
0002 JC002 2
0003 JC003 1
0004 JC004 1
0004 JC004 2
0004 JC004 3
My try:
update employee t1
join
(
select emp_id ,job_code ,row_number() over(partition by emp_id ,job_code ) rnk
from employee
) t2
on t1.emp_id = t2.emp_id and t1.job_code = t2.job_code
set t1.cnt_check = t2.rnk;
But all records getting updated with value 1.
2
Answers
Using the exact columns in your sample data, we can try:
Note that I suggest not doing this update, as every time your data changes you might have to run the update again.
You may use generation which uses BEFORE INSERT trigger and additional table:
DEMO fiddle