Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TSQL - Update table from itself

Table Item (4 columns, simplified for the sake of clarity)

Record | Item | Price | Zone

Data

1      | 100  | 10.00 | A
2      | 100  | NULL  | B
3      | 100  | NULL  | C
4      | 200  | 25.00 | A
5      | 200  | NULL  | B

Trying to update the NULLs with the corresponding values from the non-NULLs based on Item. So all Item 100s would read 10.00 and both Item 200s would read 25.00.

I feel like this should be super easy, but can't figure out the self reference.

Thanks

like image 677
FreeMars Avatar asked Aug 27 '12 23:08

FreeMars


People also ask

How do I update a table in SQL?

The first part, ' UPDATE X ' is simply ' UPDATE ' followed by the alias of the table (you don't need to say the table's name there) And (contrary to what some internet randos will tell you) you don't need to add a where clause to stop the update from applying to all rows of the table.

What is the use of conditional update in SQL?

The conditional update statement is used to change the data that satisfies the WHERE condition. However, for different scenarios, this constant value usage type cannot be enough for us, and we need to use other tables’ data in order to update our table.

What is the syntax for update statement that joins with another table?

Despite writing T-SQL day in day out since forever, I often forget the syntax for an UPDATE statement that JOINS with another table (possibly itself). So here it is: The first part, ' UPDATE X ' is simply ' UPDATE ' followed by the alias of the table (you don't need to say the table's name there)

How do I update a table without adding a where clause?

So here it is: The first part, ' UPDATE X ' is simply ' UPDATE ' followed by the alias of the table (you don't need to say the table's name there) And (contrary to what some internet randos will tell you) you don't need to add a where clause to stop the update from applying to all rows of the table.


1 Answers

here u go

UPDATE a
SET a.Price=b.Price
FROM  Item AS a
INNER JOIN Item AS b
ON a.item=b.item
WHERE a.Price is NULL AND b.price is NOT NULL

or if there are multiple Non-null prices and you want to choose maximum price.

 UPDATE a
 SET a.Price=(SELECT MAX(b.PRICE) FROM ITEM AS b WHERE b.Item=a.Item and b.Price is not null )
 FROM  Item AS a
 WHERE a.Price is NULL  
like image 198
ClearLogic Avatar answered Oct 24 '22 07:10

ClearLogic