0

我正在使用以下代码在 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')

我需要删除值前面的“十进制”字符串。

我尝试使用过去示例中的以下内容

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')
4

1 回答 1

1

更改查询的顺序以获得您想要的顺序(名称然后成绩)

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
于 2014-10-10T20:26:45.037 回答