简体   繁体   中英

Update row SQL in same table with data from other row

I'm stuck with making a SQL query to update different rows, all in the same table. But 1 row has to get data from another row which has the same reference ID ( bst__ref ).

CURRENT TABLE bstlyn__

A B C D E F G
157035 1/01/1980 2/04/2021 117210 N 0 N
157035 1/01/1980 25/03/2021 128078 N 0 N
157035 1/01/1980 25/03/2021 128078 N 0 N
157036 1/01/1980 12/04/2021 117022 N 0 N
157036 1/01/1980 12/04/2021 117034 N 0 N
157036 1/01/1980 9/04/2021 128078 N 0 N

CURRENT SQL QUERY

UPDATE bstlyn__ SET G = 'Y', F = 'N', B = C WHERE E = 'N' AND F = '0'

This causes to change all vrz__dat lines to the same value as in vrzv_dat . But as you can see within the same bst__ref , the vrzv_dat of all afg__ref 's with value 128078 have a different vrzv_dat . This should be the same date/ vrz__dat like the (first) row from that bst__ref which hasn't got afg__ref 128078.

So, after running the query above I get:

bst__ref (A) vrz__dat (B) vrzv_dat (C) afg__ref (D) fiat____ (E) fac__tst (F) vrz__tst (G)
157035 2/04/2021 2/04/2021 117210 N N Y
157035 25/03/2021 25/03/2021 128078 N N Y
157035 25/03/2021 25/03/2021 128078 N N Y
157036 12/04/2021 12/04/2021 117022 N N Y
157036 12/04/2021 12/04/2021 117034 N N Y
157036 9/04/2021 9/04/2021 128078 N N Y

But it should be:

bst__ref vrz__dat vrzv_dat afg__ref fiat____ fac__tst vrz__tst
157035 2/04/2021 2/04/2021 117210 N N Y
157035 2/04/2021 25/03/2021 128078 N N Y
157035 2/04/2021 25/03/2021 128078 N N Y
157036 12/04/2021 12/04/2021 117022 N N Y
157036 12/04/2021 12/04/2021 117034 N N Y
157036 12/04/2021 9/04/2021 128078 N N Y

How on Earth can I do this with only using SQL? Thanks!

You can use this table twice, you just need to alias the table in the subqueries. Then perform retrieval only of the first for each same A code

try this code:

UPDATE bstlyn__ t, (SELECT DISTINCT A,B,C,D,E,F,G
                    FROM bstlyn__ ) t1
SET t.B = t1.C, G = 'Y', F = 'N'
WHERE t.A= t1.A

You need to correlate back to the same table. There are various ways of accomplishing this, you appear to want to do this specifcally on a single value, so if I have understood correctly you can try this

update b set 
vrz__tst = 'Y',
fac__tst = 'N',
vrz__dat = 
    case when afg_ref=128078 then 
        (select Min(vrzv_dat) from bstlyn__ b2 where b2.bst_ref=b.bst_ref)
    else vrzv_dat end
from  bstlyn__ b
where fiat____ = 'N' and fac__tst = '0'

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