【问题标题】:Update PostgresSQL column with computed data from the same table使用来自同一表的计算数据更新 PostgreSQL 列
【发布时间】:2021-04-26 13:16:33
【问题描述】:

我需要根据同一表中的信息更新 PostgreSQL 表中的值。

例如表格是这样的

更新前

index shop_id tire_type count
0 0 Winter Null
1 0 Summer Null
2 0 Winter Null
3 0 Winter Null
4 1 Summer Null
5 1 Winter Null

更新后

index shop_id tire_type count
0 0 Winter 3
1 0 Summer 1
2 0 Winter 3
3 0 Winter 3
4 1 Summer 1
5 1 Winter 1

对于此示例,该表包含通过 shop_id 连接到 shop 表的轮胎类型。 count 列应该包含相同 shop_id 上相同轮胎类型的数量。

从上面的例子我们可以看到 shop_id = 0 的 Winter 类型的数量是 3 所以每一行 Winter 类型的 count 列中应该有数字 3。

如何用 SQL 来做到这一点?或者在现有 DataFrame 上使用 Python Pandas DataFrame(将插入现有 PostgresSQL 表中)?

附:无法更改表架构。首选的解决方案是使用 Pandas,但也可以使用 PostgreSQL。

【问题讨论】:

    标签: python sql pandas postgresql


    【解决方案1】:

    使用Groupby.transform:

    In [30]: df['count'] = df.groupby(['shop_id', 'tire_type'])['count'].transform('count')
    
    In [31]: df
    Out[31]: 
       index  shop_id tire_type  count
    0      0        0    Winter      3
    1      1        0    Summer      1
    2      2        0    Winter      3
    3      3        0    Winter      3
    4      4        1    Summer      1
    5      5        1    Winter      1
    

    然后使用df.to_sql 将此df 写回Postgres

    【讨论】:

      【解决方案2】:

      你可以使用窗口函数:

      select t.*,
             count(*) over (partition by tire_type, shop_id)
      from t;
      

      如果您需要更新值,则可以在update 语句中使用聚合:

      update t
          set count = tt.cnt
          from (select tire_type, shop_id, count(*) as cnt
                from t
                group by tire_type, shop_id
               ) tt
          where t.tire_type = tt.tire_type and t.shop_id = tt.shop_id
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-06-16
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-10-12
        • 1970-01-01
        • 2021-12-27
        相关资源
        最近更新 更多