![](/img/trans.png)
[英]SQL: Update table with alternative values from same table if values are missing
[英]SQL update missing values from same table
如果我有这张桌子
---------- ----------
jones new york
jones
richard seattle
jones
richard
Ellen Vancouver
Ellen
我想要这张新桌子
---------- ----------
jones new york
jones new york
richard seattle
jones new york
richard seattle
Ellen Vancouver
Ellen Vancouver
我该如何更新? 我正在使用Postgresql。
最好的解决方案是适当地标准化表,以便在它们之间创建一对一的连接表,该表将每个名称连接到一个城市,如果实际上每个名称应该恰好一个城市。
给定您所拥有的,您可以在FROM
子句中提供一个子查询,该子查询返回每个name
组的MAX(city)
。 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;
这是一个演示: http : //sqlfiddle.com/#! 1/6ad17/1
这是一个有效的临时表解决方案。 您应该能够对问题应用相同的逻辑。
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.