Postgresql中的更新计数列
我有一张这样的桌子:Postgresql中的更新计数列,postgresql,Postgresql,我有一张这样的桌子: id | name | count 1 | John | 2 | Jim | 3 | John | 4 | Tim | 我需要填写count列,以便结果是特定名称在列name中显示的次数 结果应该是: id | name | count 1 | John | 2 2 | Jim | 1 3 | John | 2 4 | Tim | 1 我可以使用以下方法轻松获得唯一名称的出现
id | name | count
1 | John |
2 | Jim |
3 | John |
4 | Tim |
我需要填写count列,以便结果是特定名称在列name
中显示的次数
结果应该是:
id | name | count
1 | John | 2
2 | Jim | 1
3 | John | 2
4 | Tim | 1
我可以使用以下方法轻松获得唯一名称的出现次数:
SELECT COUNT(name)
FROM table
GROUP BY name
但这不适合UPDATE
语句,因为它返回多行
我还可以通过这样做将其缩小到一行:
SELECT COUNT(name)
FROM table
WHERE name = 'John'
GROUP BY name
但这不允许我填写整个列,只填写“John”行。您可以使用一个通用的表表达式:
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;
另一个(较慢的)选项是使用相关子查询:
update the_table
set "count" = (select count(*)
from the_table t2
where t2.name = the_table.name);
但总的来说,存储易于动态计算的值是一个坏主意:
select id,
name,
count(*) over (partition by name) as name_count
from the_table;
另一种方法:使用派生表
UPDATE tb
SET count = t.count
FROM (
SELECT count(NAME)
,NAME
FROM tb
GROUP BY 2
) t
WHERE t.NAME = tb.NAME
一定要注意
一般来说,存储易于计算的值是一个不好的主意