简体   繁体   中英

SQL-Oracle: Updating table multiple row based on values contained in the same table

I have one table named: ORDERS

this table contains OrderNumber's which belong to the same person and same address lines for that person.

However sometimes the data is inconsistent; as example looking at the table screenshot: Orders table with bad data to fix -

you all can noticed that orderNumber 1 has a name associated to and addresses line1-2-3-4. sometimes those are all different by some character or even null.

my goal is to update all those 3 lines with one set of data that is already there and set equally all the 3 rows.

to make more clear the result expected should be like this:

enter image description here

i am currently using a MERGE statement to avoid a CURSOR (for loop )

but i am having problems to make it work

here the SQL

    MERGE INTO ORDERS O USING
    (SELECT
     INNER.ORDERNUMBER,
      INNER.NAME,
      INNER.LINE1,
      INNER.LINE2,
      INNER.LINE3,
      INNER.LINE4
    FROM ORDERS INNER
      ) TEMP 
ON( O.ORDERNUMBER  = TEMP.ORDERNUMBER  )
WHEN MATCHED THEN
  UPDATE
  SET 
          O.NAME = TEMP.NAME,
          O.LINE1 = TEMP.LINE1,
          O.LINE2 = TEMP.LINE2,
          O.LINE3 = TEMP.LINE3,
          O.LINE4 = TEMP.LINE4;

the biggest issues i am facing is to pick a single row out of the 3 randomly - it does not matter whihc of the data - row i pick to update the line/s as long i make the records exaclty the same for an order number.

i also used ROWNUM =1 but it in multip[le updates will only output one row and update maybe thousand of lines with the same address and name whihch belong to an order number.

order number is the join column to use ...

kind regards

A simple correlated subquery in an update statement should work:

update orders t1
   set (t1.name, t1.line1, t1.line2, t1.line3, t1.line4) =
          (select t2.name, t2.line1, t2.line2, t2.line3, t2.line4
             from orders t2
            where t2.OrderNumber = t1.OrderNumber
              and rownum < 2)

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