Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server - Update column from data in the same table

Tags:

sql

sql-server

I have a table that looks something like this:

SetId      ID       Premium 2012        5          Y 2012        6          Y 2013        5          N 2013        6          N 

I want to update the 2013 records with the premium values where the setid equals 2012.

So after the query it would look like this:

SetId      ID       Premium 2012        5          Y 2012        6          Y 2013        5          Y 2013        6          Y 

Any help greatly appreciated

like image 591
dawsonz Avatar asked Sep 30 '13 12:09

dawsonz


People also ask

How can I update one column from another column in the same table in SQL Server?

In such a case, you can use the following UPDATE statement syntax to update column from one table, based on value of another table. UPDATE first_table, second_table SET first_table. column1 = second_table. column2 WHERE first_table.id = second_table.

How do you update a column based on another column in a table?

UPDATE table SET col = new_value WHERE col = old_value AND other_col = some_other_value; UPDATE table SET col = new_value WHERE col = old_value OR other_col = some_other_value; As you can see, you can expand the WHERE clause as much as you'd like in order to filter down the rows for updating to what you need.


2 Answers

UPDATE t  SET t.Premium = (SELECT TOP 1 t2.Premium                  FROM dbo.TableName t2                  WHERE t2.SetId = 2012) FROM dbo.TableName t WHERE t.SetId = 2013  

Demonstration

like image 42
Tim Schmelter Avatar answered Sep 21 '22 09:09

Tim Schmelter


It's not clear which 2012 value you want to use to update which 2013 value, i've assumed that the ID should be the same.

Full example using table variables that you can test yourself in management studio.

DECLARE @Tbl TABLE (     SetId INT,     Id INT,      Premium VARCHAR(1) )  INSERT INTO @Tbl VALUES (2012, 5, 'Y') INSERT INTO @Tbl VALUES (2012, 6, 'Y') INSERT INTO @Tbl VALUES (2013, 5, 'N') INSERT INTO @Tbl VALUES (2013, 6, 'N')  --Before Update SELECT * FROM @Tbl   --Something like this is what you need UPDATE t  SET t.Premium = t2.Premium  FROM @Tbl t  INNER JOIN @Tbl t2 ON t.Id = t2.Id  WHERE t2.SetId = 2012 AND t.SetId = 2013  --After Update     SELECT * FROM @Tbl  
like image 197
Chris Diver Avatar answered Sep 21 '22 09:09

Chris Diver