我正在使用以下代码在 Python 中运行 MySql 查询:
cur = conn.cursor()
query = ("""select sum(if(grade is not null,1,0)) as `test`,
sum(if(grade < 7,1,0)) as `bad`,
sum(if(grade < 7,1,0))/sum(if(grade is not null,1,0))*100 as `Pct Bad Grade`,
student
from grades_database
where test_date >= '2014-08-01'
group by student
order by `Pct Bad Grade` desc;""")
cur.execute(query)
我得到了类似的结果
(Decimal('1'), Decimal('3'), Decimal('50.0000'), 'John Doe')
我需要删除值前面的“Decimal”字符串。
我尝试使用 Past Example 中的以下内容
output = []
for row in cur:
output.append(float(row[0]))
print output
但它给了我这个
[20.0, 5.0, 3.0, 7.0, 7.0, 2.0, 6.0, 7.0, 7.0, 7.0,...]
理想情况下,我想重新排列输出的顺序并得到类似的内容
(John Doe, 50, 3, 1)]
来自
(Decimal('1'), Decimal('3'), Decimal('50.0000'), 'John Doe')
最佳答案
更改查询的顺序以获得所需的顺序(姓名,然后成绩)
cur = conn.cursor()
query = ("""select student,
sum(if(grade is not null,1,0)) as `test`,
sum(if(grade < 7,1,0)) as `bad`,
sum(if(grade < 7,1,0))/sum(if(grade is not null,1,0))*100 as `Pct Bad Grade`
from grades_database
where test_date >= '2014-08-01'
group by student
order by `Pct Bad Grade` desc;""")
cur.execute(query)
然后您可以更改十进制值,因此跳过第一个索引(名称)。
for index, row in enumerate(cur):
if index:
output[index] = int(row)
print output
关于python - 如何在 Python 中从 MySQL 查询结果追加 "Decimal",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26304112/