postgresql 从现有列创建新列而不是更新

8fsztsew  于 2023-06-22  发布在  PostgreSQL
关注(0)|答案(1)|浏览(128)

我有这样的数据:

create table mytest (
staff_n int,
emp_name text
);

insert into mytest values (1,'James'),(1,'James H'),(2,'B Hua'),(2,'B Huatur');

1   "James"
1   "James H"
2   "B Hua"
2   "B Huatur"

我们的目标是用id规范化名称,以便每个id只有名称的max()。我用这个查询成功地更新了列。

with temp_t as (
select staff_n,max(emp_name) as max_emp from mytest
group by staff_n)
update mytest
set emp_name = max_emp
from temp_t
where mytest.staff_n = temp_t.staff_n;

导致以下数据:
但我真的很想有一个额外的列,说emp_name_normalized,并留下一个更新不变。预期输出为:

staff_n  emp_name   epm_name_normalized
1   "James"       "James H"
1   "James H"     "James H"
2   "B Hua"       "B Huatur"
2   "B Huatur"    "B Huatur"
mbzjlibv

mbzjlibv1#

首先,需要添加列emp_name_normalized

ALTER TABLE mytest
ADD COLUMN emp_name_normalized varchar(20);

然后使用查询填充emp_name_normalized

with temp_t as (
  select staff_n, max(emp_name) as max_emp from mytest
  group by staff_n
)
update mytest
set emp_name_normalized = max_emp
from temp_t
where mytest.staff_n = temp_t.staff_n;

Demo here

相关问题