[英]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. 我的SQL版本找不到当前问题的答案,因此希望有人可以帮助我。
I am using MySQL with SQLPro as the client or I can use PostgreSQL pgAdmin 4. 我将MySQL和SQLPro用作客户端,或者可以使用PostgreSQL pgAdmin 4。
scenario I am trying to update a null
value with the previous not null value
. 情景我尝试更新null
与前值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? 如何用not null values
填充null
值,以便address/ID
分组在我的列中保持不变?
thanks!!! 谢谢!!!
If you want to update the table, this will work in Postgres: 如果要更新表,则可以在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: 在MySQL中,这将起作用:
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: 我将您的表插入在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. 因此,我的想法是,我抓取所有所有非空地址和id组(假设地址始终与相同的id配对。我将此称为_users。
Match _users.address with your original users.address. 将_users.address与原始的users.address匹配。 Make sure that you are only updating the NULL users.id. 确保仅更新NULL users.id。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.