简体   繁体   中英

SQL Server - Update column from data in the same table

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

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 
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

I think this is correct solution:

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

We can update table from self table, like this:

update TABLE_A 
   set TABLE_A.Col1=B.Col2
  from TABLE_A B 

There is ABSOLUTELY no need to go to all those fancy lengths suggested by the accpeted answer using INNER JOIN s or FROM s or aliases when updating from the same table - see the fiddle here !

CREATE TABLE b (x INT, y INT);

Populate:

INSERT INTO b (x) VALUES (2), (3), (4);

Check:

SELECT * FROM test;

Result:

x   y
2   null
3   null
4   null

Now - just simply:

UPDATE b SET y = x
WHERE x <= 3;

Then:

SELECT * FROM b;

Result:

x   y
2   2
3   3
4   null

Et voilà - perfectly simple! Antoine de Saint-Exupéry was right :

“La perfection est atteinte, non pas lorsqu'il n'y a plus rien à ajouter, mais lorsqu'il n'y a plus rien à retirer.”


Perfection is achieved, not when there is nothing more to add, but when there is nothing left to take away.

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