I have a following PostgreSQL table:
CREATE TABLE users (
user_id INTEGER DEFAULT nextval('users_user_id_seq') NOT NULL,
user_old_id CHARACTER VARYING(36),
created_by INTEGER,
created_by_old character varying(36),
last_updated_by INTEGER,
last_updated_by_old character varying(36),
CONSTRAINT users_pkey PRIMARY KEY (user_id)
);
Based on data in this table I need to update:
created_byfield withuser_idfrom this table for every row wherecreated_by_old = user_old_idPlease note thatcreated_by_oldcan be NULL and therefore must be avoided in this case.last_updated_byfield withuser_idfrom this table for every row wherelast_updated_by_old = user_old_idPlease note thatlast_updated_by_oldcan be NULL and therefore must be avoided in this case.
This is a sample data:
Actual:
user_id | user_old_id | created_by | created_by_old | last_updated_by | last_updated_by_old
--------------------------------------------------------------------------------------------
1 | aaa | | ccc | | bbb
--------------------------------------------------------------------------------------------
2 | bbb | | ddd | | aaa
--------------------------------------------------------------------------------------------
3 | ccc | | | | ddd
--------------------------------------------------------------------------------------------
4 | ddd | | aaa | |
Expected:
user_id | user_old_id | created_by | created_by_old | last_updated_by | last_updated_by_old
--------------------------------------------------------------------------------------------
1 | aaa | 3 | ccc | 2 | bbb
--------------------------------------------------------------------------------------------
2 | bbb | 4 | ddd | 1 | aaa
--------------------------------------------------------------------------------------------
3 | ccc | | | 4 | ddd
--------------------------------------------------------------------------------------------
4 | ddd | 1 | aaa | |
I think it can be implemented with a subquery but can't figure out by myself right now how to implement this query. Please help.