[英]Update PostgresSQL column with computed data from the same table
我需要根據來自同一表的信息更新 PostgreSQL 表中的值。
例如表格看起來像這樣
更新前:
指數 | shop_id | 輪胎類型 | 數數 |
---|---|---|---|
0 | 0 | 冬天 | Null |
1 | 0 | 夏天 | Null |
2 | 0 | 冬天 | Null |
3 | 0 | 冬天 | Null |
4 | 1 | 夏天 | Null |
5 | 1 | 冬天 | Null |
更新后:
指數 | shop_id | 輪胎類型 | 數數 |
---|---|---|---|
0 | 0 | 冬天 | 3 |
1 | 0 | 夏天 | 1 |
2 | 0 | 冬天 | 3 |
3 | 0 | 冬天 | 3 |
4 | 1 | 夏天 | 1 |
5 | 1 | 冬天 | 1 |
對於此示例,該表包含通過 shop_id 連接到 shop 表的輪胎類型。 count 列應該包含相同 shop_id 上相同輪胎類型的數量。
從上面的示例中我們可以看到 shop_id = 0 處 Winter 類型的數量為 3,因此 Winter 類型的每一行在 count 列中應該有數字 3。
SQL 如何做到這一點? 或者使用 Python Pandas DataFrame 在現有的 ZBA834BA059A9A379444ZSQL 上存在的表?
PS 表架構無法更改。 首選的解決方案是使用 Pandas,但也可以使用 PostgreSQL。
您可以使用 window 函數:
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
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
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.