2014-10-10 33 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