Postgresql中的“更新计数”列

Jos*_*osh 1 postgresql

我有一张这样布置的桌子:

id  |  name  |  count
1   |  John  |
2   |  Jim   |
3   |  John  |
4   |  Tim   |
Run Code Online (Sandbox Code Playgroud)

我需要填写count列,以便结果是特定名称在该列中显示的次数name

结果应为:

id  |  name  |  count
1   |  John  |  2
2   |  Jim   |  1
3   |  John  |  2
4   |  Tim   |  1
Run Code Online (Sandbox Code Playgroud)

我可以使用以下方法轻松获得唯一名称的出现次数:

SELECT COUNT(name)
FROM table
GROUP BY name
Run Code Online (Sandbox Code Playgroud)

但这不适合UPDATE语句,因为它返回多行。

通过执行以下操作,我还可以将其缩小到一行:

SELECT COUNT(name)
FROM table
WHERE name = 'John'
GROUP BY name
Run Code Online (Sandbox Code Playgroud)

但这不允许我填写整个列,仅填写“ John”行。

a_h*_*ame 7

您可以使用通用表表达式来做到这一点:

with counted as (
   select name, count(*) as name_count
   from the_table
   group by name
) 
update the_table
  set "count" = c.name_count
from counted c
where c.name = the_table.name;
Run Code Online (Sandbox Code Playgroud)

另一个(较慢的)选择是使用与相关的子查询:

update the_table
  set "count" = (select count(*) 
                 from the_table t2 
                 where t2.name = the_table.name);
Run Code Online (Sandbox Code Playgroud)

但是通常来说,存储可以轻松地即时计算的值是一个坏主意:

select id,
       name, 
       count(*) over (partition by name) as name_count
from the_table;
Run Code Online (Sandbox Code Playgroud)