【问题标题】:Update Count column in PostgresqlPostgresql 中的更新计数列
【发布时间】:2015-09-03 12:46:55
【问题描述】:

我有一个这样布置的表:

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”行。

【问题讨论】:

    标签: postgresql


    【解决方案1】:

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

    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;
    

    【讨论】:

    • 请注意in general it is a bad idea to store values that can easily be calculated(感谢a_horse_with_no_name)
    【解决方案2】:

    另一种方法:使用派生表

    UPDATE tb
    SET count = t.count
    FROM (
        SELECT count(NAME)
            ,NAME
        FROM tb
        GROUP BY 2
        ) t
    WHERE t.NAME = tb.NAME
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-01-28
      • 2019-10-14
      • 1970-01-01
      • 2022-11-22
      • 2023-02-07
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多