简体   繁体   中英

SQLPro or PostgreSQL SQL updating row based on previous row value

I can't find the answer to the current question with my versions of SQL so hopefully someone can help me out.

I am using MySQL with SQLPro as the client or I can use PostgreSQL pgAdmin 4.

scenario I am trying to update a null value with the previous not null value .

here is my table:

primary_id  name  address  id
1           bob   123 main 100
2           jane  123 main NULL
3           mike  217 2nd  200
4           jeff  217 2nd  NULL

在此处输入图片说明

How can I populate the null values with the not null values so that the address/ID grouping remain constant down my columns?

thanks!!!

If you want to update the table, this will work in Postgres:

update t
    set id = (select t2.id
              from t t2
              where t2.address = t.address and t2.id is not null
              fetch first 1 row only
             )
    where id is null;

In MySQL, this will work:

update t join
       (select address, max(id) as max_id
        from t
        group by address
       ) tt
       on t.address = tt.address
    set t.id = tt.max_id
    where t.id is null;

You can try updating the table with itself. I inserted your table into a users table I created in postgres:

UPDATE users
  SET
    id = _users.id
FROM
(
  SELECT DISTINCT
    address,
    id
    FROM users
    WHERE id IS NOT NULL
    GROUP BY
      address,
      id
) _users
WHERE
    _users.address = users.address
    AND users.id IS NULL;

So the idea is that I grab all all the non-null address and id groups (assuming address is always paired with the same id. I call this _users.

Match _users.address with your original users.address. Make sure that you are only updating the NULL users.id.

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