![](/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.