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

2024-06-08 05:04:31 发布

您现在位置:Python中文网/ 问答频道 /正文

我有4列的主席表,分别是id,name,vots,给定百分比(1,2,3,4,5)是ID,想根据每个候选人的票数来计算每个的百分比。我尝试了这个,但它给了我一个错误,不支持/:“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))


Tags: namefromselfidexecutecountwhereselect
2条回答

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

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

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

看起来counttotal都包含一整行结果。再使用[0]索引一次,以获得所需的值。你知道吗

相关问题 更多 >

    热门问题