Home > Back-end >  Change values to repeat based when a condition is met in SQL
Change values to repeat based when a condition is met in SQL

Time:10-27

enter image description here

I want to create a new column where If my Rom Indicator is 'Y', then pick the Account ID value and swap it for all the IDs as shown below

enter image description here

I tried using Case statments like this CASE WHEN PRIM_IND = 'Y' THEN ACT_ID ELSE ACT_ID END

CodePudding user response:

select  t.*
       ,max(case when PRI_IND = 'Y' then ACT_ID end) over(partition by ID) as ACT_ID_NEW
from    t  
ID ACT_ID PRI_IND ACT_ID_NEW
200 ACT01 N ACT02
200 ACT02 Y ACT02
201 ACT03 Y ACT03
201 ACT04 N ACT03
201 ACT05 N ACT03
202 ACT06 Y ACT06

Fiddle

CodePudding user response:

Not sure if this is what you wanted, but the output matches so I guess so. It's just a basic self INNER JOIN where you only want to join on the records with pri_ind = 'Y'

SELECT a.id,
       a.act_id,
       a.pri_ind,
       b.act_id AS act_id_new
FROM   tab1 a
       INNER JOIN tab1 b
               ON a.id = b.id
                  AND b.pri_ind = 'Y' 
  • Related