[英]SQL update missing values from same table
If I have this table 如果我有这张桌子
---------- ----------
jones new york
jones
richard seattle
jones
richard
Ellen Vancouver
Ellen
And I want this new table 我想要这张新桌子
---------- ----------
jones new york
jones new york
richard seattle
jones new york
richard seattle
Ellen Vancouver
Ellen Vancouver
How can I update it? 我该如何更新? I am using Postgresql.
我正在使用Postgresql。
The best solution would be to properly normalize the tables such that a one to one join table was created between them which joins each name to a single city, if indeed there should be exactly one city per name. 最好的解决方案是适当地标准化表,以便在它们之间创建一对一的连接表,该表将每个名称连接到一个城市,如果实际上每个名称应该恰好一个城市。
Given what you have though, you may supply a subquery in the FROM
clause which returns the MAX(city)
per name
group. 给定您所拥有的,您可以在
FROM
子句中提供一个子查询,该子查询返回每个name
组的MAX(city)
。 From there the SET
clause updates the main table's city
to the value returned by the subquery. SET
子句从那里将主表的city
更新为子查询返回的值。
UPDATE
tbl t
SET
city = c.city
FROM
/* Subquery in FROM returns first (max()) non-null city per name */
(SELECT name, MAX(city) AS city FROM tbl WHERE city IS NOT NULL GROUP BY name) c
WHERE
/* Only update non-null cities */
t.city IS NULL
/* Here's the joining relation to the subquery */
AND t.name = c.name;
Here's a demo: http://sqlfiddle.com/#!1/6ad17/1 这是一个演示: http : //sqlfiddle.com/#! 1/6ad17/1
Here is a solution with a temp table that works. 这是一个有效的临时表解决方案。 You should be able to apply the same logic to your issue.
您应该能够对问题应用相同的逻辑。
create temp table foo(employee_name text, city text);
insert into foo (employee_name, city) values
('jones', 'new york'),
('jones', NULL),
('richard', 'seattle'),
('richard', NULL),
('ellen', 'vancouver'),
('ellen', NULL);
update foo f set city = x.city
from foo x
where f.employee_name = x.employee_name
and f.city is null;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.