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 NULL
s with the corresponding values from the non-NULL
s 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
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.
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.
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)
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With