简体   繁体   中英

Updating multiple rows dynamically according to a value in another table oracle sql

table 1 : employee id (ex.: 100000) | status ((A)ctive/(I)nactive)

table 2 : group (ex.:'ABC') | emplid (ex.: 100000) | has_documents((Y)es/(N)o)

I am trying to update a table in order to set every employees that is active to the state of has _document = 'Y' and every employees thats inactive to has_documents = 'N'. An employee can be in multiple groups and has to be in a 'Y' state on every row containing its employee id if his state is active

This is a query I currently have:

UPDATE table2 t2 SET has_documents = 
(SELECT (CASE WHEN(
SELECT t1.HR_STATUS
FROM table1 t1
WHERE t1.EMPLID = t2.EMPLID ) = 'A' THEN 'Y' ELSE 'N' END) FROM DUAL);

And it returns the following error : single-row subquery returns more than one row

I have also tried this query which returned the same error :

UPDATE SYSADM.PS_RH_EE_LITIGATN P
  SET RH_RR_DOC = (SELECT 
    (CASE WHEN 
        (SELECT J.HR_STATUS FROM PS_JOB_CURR_VW J 
        JOIN SYSADM.PS_RH_EE_LITIGATN L 
        ON J.EMPLID = L.EMPLID WHERE J.EMPLID = P.EMPLID) 
    = 'A' THEN 'Y' ELSE 'N' END) FROM DUAL);

example data :

table 1:           table2:
empli_id | status  group | empli_id | has_docs
100000   | A       'ABC' | 100002   | null
100001   | I       'XYZ' | 100002   | null
100002   | A       'ABC' | 100001   | null
100003   | A       'ABC' | 100003   | null
100004   | I       'XYZ' | 100004   | null

Desired Result :

table 1:           table2:
empli_id |status   group | empli_id | has_docs
100000   | A       'ABC' | 100002   | Y
100001   | I       'XYZ' | 100002   | Y
100002   | A       'ABC' | 100001   | N
100003   | A       'ABC' | 100003   | Y
100004   | I       'XYZ' | 100004   | N

You can use merge statement as following:

Merge into table2 t2
Using (select * from table1) t1
On (t1.empli_id = t2.empli_id)
When matched then 
Update set t2.has_document = decode(t1.status, 'A', 'Y', 'N')

Cheers!!

Employee may be in two groups, so use conditional aggregation and count inactive rows. Use such prepared data in merge statement and set has_docs to Y if cnt_inactive is 0, N otherwise.

dbfiddle demo

merge into table2 tgt
using (select empli_id, count(case status when 'I' then 1 end) cnt_inactive
         from table1 group by empli_id) src
on (tgt.empli_id = src.empli_id)
when matched then update set 
    has_docs = case cnt_inactive when 0 then 'Y' else 'N' end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM