2014-10-10 59 views
0

我使用下面的代码运行在Python MySQL查询:如何从MySQL查询结果追加“十进制”在Python

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)] 

from

(Decimal('1'), Decimal('3'), Decimal('50.0000'), 'John Doe') 
+0

“小数”对象比“浮动”对象更精确。当你打印或写入数据时,你只会得到数值,例如:'print Decimal('50 .0000')'给出:'50.0000'。 – bernie 2014-10-10 16:45:08

回答

0

更改您的查询的顺序,以获得您想要的顺序(名称,然后等级)

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