gpt4 book ai didi

postgresql - 更新 Postgresql 中的计数列

转载 作者:行者123 更新时间:2023-11-29 12:29:54 26 4
gpt4 key购买 nike

我有一个这样布置的表:

id  |  name  |  count
1 | John |
2 | Jim |
3 | John |
4 | Tim |

我需要填写计数列,以便结果是特定名称在列 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;

关于postgresql - 更新 Postgresql 中的计数列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32361457/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com