如何使用 Python 更新 PostgreSQL 中通过 SELECT 查询获得的行? Python 2.7 psycopg2
How can I update rows obtained by a SELECT query in PostgreSQL with Python? Python 2.7 psycopg2
我有以下代码来计算我 table 的特定行中的值:
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
我需要做的是将 percentile
结果添加到我通过 SELECT
查询获得的每条记录的相应列 score_percentile
。
我考虑过这样的 UPDATE
查询:
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;")
我通过以下方式获得了 group_size
:
cursor.execute("SELECT COUNT(*) FROM restaurants WHERE license_type_code='20'")
group_size = cursor.fetchone()
group_size = group_size[0]
这非常适合我的情况
我有以下代码来计算我 table 的特定行中的值:
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
我需要做的是将 percentile
结果添加到我通过 SELECT
查询获得的每条记录的相应列 score_percentile
。
我考虑过这样的 UPDATE
查询:
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;")
我通过以下方式获得了 group_size
:
cursor.execute("SELECT COUNT(*) FROM restaurants WHERE license_type_code='20'")
group_size = cursor.fetchone()
group_size = group_size[0]
这非常适合我的情况