繁体   English   中英

如何使用python计算MySQL数据库中给定列的表中每一行的百分比

[英]how to calculate the percentage for each row in table in for given column in MySQL database using python

我有 4 列是 id,name,votes,percentage.given (1,2,3,4,5) 是 ids 的表总统,想根据每个候选人的票数计算每个人的百分比. 我试过这个,但它给了我一个错误,即 / :'turple' 和 'turple' 的操作数类型不受支持。 如果有人帮助,我将不胜感激

self.cursor.execute("""select sum(votes) from president""") total=self.cursor.fetchall()[0] for i in range(1,6): self.cursor.execute("""select votes from president where id = %s""",i) count = self.cursor.fetchone()[0] self.cursor.execute("""update presidents SET percentage = %s where id =%s""",((count/total),i))

看起来counttotal都包含一整行结果。 再用[0]对它们进行索引以获取您需要的值。

total被设置为一个元组,因为您使用的是fetchall ,它返回一个行元组列表。 改用fetchone来解决这个问题。

cursor.execute严格要求一个元组作为它的第二个参数。 因此,循环中的第一个调用应为

self.cursor.execute("""select count(votes) from president where id = %s""",(i, ))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM