如何使用Python更新PostgreSQL中SELECT查询获得的行?Python 2.7 psycopg2

如何使用Python更新PostgreSQL中SELECT查询获得的行?Python 2.7 psycopg2,python,sql,postgresql,python-2.7,psycopg2,Python,Sql,Postgresql,Python 2.7,Psycopg2,我有以下代码来计算表中特定行中的值: cursor.execute("SELECT * FROM restaurants WHERE license_type_code='20' ORDER BY general_score DESC;") group_size = cursor.rowcount for record in cursor: index = cursor.rownumber percentile = 100*(index - 0.5)/group_size pr

我有以下代码来计算表中特定行中的值:

cursor.execute("SELECT * FROM restaurants WHERE license_type_code='20' ORDER BY general_score DESC;")
group_size = cursor.rowcount
for record in cursor:
   index = cursor.rownumber
   percentile = 100*(index - 0.5)/group_size
   print percentile
我需要做的是将百分位数结果添加到我通过SELECT查询获得的每条记录的相应列score_百分位数中

我考虑过这样一个更新查询:

 cursor.execute("UPDATE restaurants SET score_percentile="+str(percentile)+" WHERE license_type_code IN (SELECT * FROM restaurants WHERE license_type_code='20' ORDER BY general_score DESC)")
但我不知道这个问题是否正确,或者是否有一种更有效、更不愚蠢的方法可以做到这一点,我确信这是必须的。 你能帮帮我吗

我是SQL新手,因此非常感谢您的帮助或建议。
谢谢

您根本不需要循环。只需一个更新查询

cursor.execute("UPDATE restaurants SET score_percentile = 100*(rownumber - 0.5)/group_size  FROM (SELECT COUNT (*) as group_size FROM restaurants WHERE license_type_code='20') as t WHERE restaurants.license_type_code='20'")

正如Thomas所说,我只需要一个具有以下语法的更新查询:

cursor.execute("UPDATE restaurants f SET score_percentile = ROUND(100*(f2.rownumber - 0.5)/"+str(group_size)+",3) FROM (SELECT f2.*,row_number() OVER (ORDER BY general_score DESC) as rownumber FROM restaurants f2 WHERE license_type_code='20') f2 WHERE f.license_type_code='20' AND f2.license_number=f.license_number;")
我通过以下方式得出了团队规模:


这非常适合我的案例

虽然查询的语法不起作用,但您让我了解了如何解决它。谢谢
cursor.execute("SELECT COUNT(*) FROM restaurants WHERE license_type_code='20'")
group_size = cursor.fetchone()
group_size = group_size[0]