简体   繁体   中英

How to update rows values with other rows values from the same table

I have the following table:

Parameters

id, ownerId, paramId, value
1,    500,    100,    12345
2,    500,    100,    54321
3,    500,    101,      900
4,    500,    101,      901
5,    501,    101,      888
6,    501,    101,      777

Expected result:

Parameters

id, ownerId, paramId, value
1,    500,    100,      900
2,    500,    100,      901
3,    500,    101,      900
4,    500,    101,      901
5,    501,    101,      777
6,    501,    101,      777

I am trying to update the firs two rows values with the values from the last two rows, generally, I wish to update the value from 100 paramId with the value from 101 paramId where I have the same ownerId.

I am trying with the following script:

Update Parameters 
    set value = t1.value
    from Parameters t1
    where ownerId = t1.ownerId AND paramId = 100 And t1.paramId = 101

This script returns (0 row(s) affected)

both your rows with ids 3 & 4 have same data for columns ownerId, paramId and value. You will need to filter by column id to update your rows. Something like:

Update Parameters set value = (select value from Parameters where id=3) where id = 1

Update Parameters set value = (select value from Parameters where id=4) where id = 2

You may need to clarify why record 1 should be updated with the value from record 3 and record 2 should be updated with the value from record 4? But this will work otherwise...

update
    p
set 
    p.value = t.value
from 
    Parameters p
join 
    Parameters t
on
    t.ownerId = p.ownerId
    and t.paramId = 101
where
    p.paramId = 100 

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