简体   繁体   中英

SQL query to update rows based on user defined condition

I have a table and a condition to match a substring / entire value of two columns.

A sample table is like below

Table1:

id           id1    id2              id3        id4
18499       18499   8001480043398   datarow1a   datarow1a
18497       18497   8000900121777   datarow1a   datarow1a
18495       18495   8024180001901   datarow1b   datarow1b
18493       18493   8001480070530   datarow1c   something1c
18573       18573   8001480007703   datarow1b   datarow1b

Sample query with user condition:

select * 
from table1 
where id3 = id4.

Result:

id           id1    id2              id3        id4
18499       18499   8001480043398   datarow1a   datarow1a
18497       18497   8000900121777   datarow1a   datarow1a
18495       18495   8024180001901   datarow1b   datarow1b
18573       18573   8001480007703   datarow1b   datarow1b

But what I want is to update id1 to the either min or max id based on user requirement. So if the user chooses min, then id1 of rows 1 and 2 should be like below

 id          id1    id2              id3        id4
18499       18497   8001480043398   datarow1a   datarow1a
18497       18497   8000900121777   datarow1a   datarow1a

and for rows 3 and 4 it should be

18493       18493   8001480070530   datarow1c   datarow1c
18573       18493   8001480007703   datarow1b   datarow1b

Can anyone share how I should approach this?

PS: I did not know how to approach using queries, so unable to give any samples. The data base i use does not have full outer join(in case if this info is useful)

For Max:

UPDATE table_1 
SET    id1 = (SELECT Max(id1) 
          FROM   table_1 t2 
          WHERE  table_1.id3 = t2.id3) 
WHERE  id3 = id4 

For Min:

UPDATE table_1 
SET    id1 = (SELECT Min(id1) 
          FROM   table_1 t2 
          WHERE  table_1.id3 = t2.id3) 
WHERE  id3 = id4 

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