Link to home
Start Free TrialLog in
Avatar of JDCam
JDCam

asked on

SQL 2008: Update multiple columns from select of same table

Experts,
need a quick hand with this.
My table has about 90 columns. On the occasional row about 80 of the columns are null.
I am looking to update the 80 columns using information selected from any other row of the same order number.
As the null columns are all header information, they are all the same for that order number.

Here is a real simplified example of the table


Table = ORDERS						
Order	TYPE	NAME	        ADDR1	                CITY	           QTY	ITEM
101	        R	        Jon Smith	123 My Street	Toronto	      10	ABC12
101	        R	        Jon Smith	123 My Street	Toronto	       7	ABC33
101	        O	        null	                  null	                 null	               5	ABC432

Open in new window


In this example I want to update NAME, ADDR1 and CITY
where the TYPE is O  from Any line (Max or Min?) where the TYPE is R.

Please advise
Avatar of Brian Crowe
Brian Crowe
Flag of United States of America image

The process is such:
Define the logic for determining if a row needs to be updated.  NULL values in what specific columns constitute needing an update?
Define the logic for determining which other row of the same OrderID will be used to fill those gaps?  Is there a date field that can be used to select the most recent entry?

After that is done the query isn't too difficult.

BTW, does the table have a unique identifier?
What kind of table is it? Normal, report, dimension or fact?
Avatar of JDCam
JDCam

ASKER

Here is where I am at the moment..... seems like it will work.  lots of typing however to get all the columns included.

Update Orders
Set
NAME = a.NAME,
ADDR1 = a.ADDR1,
CITY = a.CITY
FROM
(Select NAME, ADDR1, CITY from ORDERS
where TYPE = 'R' and Order = 101
Group by NAME, ADDR1, CITY) as a
where Type = 'O'
Hello,

This the query which you can use for updating the record dynamically for any order rather then given hard-code value for order

update A
set 
A.NAME = B.NAME,
A.CITY = B.CITY,
A.ADDR1 = B.ADDR1
from ExcelTable A
inner join (SELECT DISTINCT [ORDER],NAME,CITY,ADDR1 FROM ExcelTable WHERE [TYPE] = 'R') B on 
A.[ORDER] = B.[ORDER]
WHERE A.TYPE = 'O'

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Vitor Montalvão
Vitor Montalvão
Flag of Switzerland image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
There is another way using merge -
merge into mytable a
using
(select distinct order, name, addr1, city
 from mytable
 where type = 'R') b
on (a.order = b.order)
when matched then
update set a.name = b.name, a.addr1 = b.addr1, a.city = b.city
where a.type = 'O';