我有一张表格如下:
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'行。
答案 0 :(得分:4)
您可以使用公用表表达式执行此操作:
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;
答案 1 :(得分:0)
另一种方法:使用派生表
UPDATE tb
SET count = t.count
FROM (
SELECT count(NAME)
,NAME
FROM tb
GROUP BY 2
) t
WHERE t.NAME = tb.NAME