python - 如何在 Python 中从 MySQL 查询结果追加 "Decimal"

标签 python mysql sql pymysql

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

相关文章:

sql - 主从复制的可靠性如何?

php - 如何解决 laravel php artisan migrate 错误问题?

php - 根据时间戳检查 DB int 字段

python - 为什么 np.argwhere 的结果形状与其输入不匹配?

python - 在 Cloud9 上运行 Python CGI

mysql - Laravel 5.2 中的批量插入优化

sql - 如何编写具有 2 个状态的查询?

php - MYSQL IF 语句到不同的 WHERE 子句

python - 如何在 pandas 中导入数字编码列?

python - 通过计算单元格中的值来计算共现矩阵