2015-04-26 83 views
0

我有一個存儲數據庫中學生分數的程序。我想爲每個學生選擇最高分數。目前,所有學生中只有一名學生得分最高,而不是每個學生的最高分數。任何人都可以幫我解決這個問題嗎? (FYI存在具有存儲在其分數的列表中的一個「分數」列)SQL選擇多個最大值和最小值 - Python

def ClassSort(): 
myFile = sqlite3.connect("scores.db") 
c = myFile.cursor() 

clear() 
classNo = input("Enter the class number you would like to sort... ") 
clear() 
type = input("How would you like to sort ? \n 1 - Highest score, with students in alphabetical order \n 2 - Highest score, highest to lowest \n 3 - Average score, highest to lowest \n... ") 

if type == "1": 
    c.execute('SELECT MIN(score), name FROM scores WHERE classNo = (?)', (classNo,))     
if type == "2": 
    c.execute('SELECT MAX(score), name FROM scores WHERE classNo = (?)', (classNo,)) 
if type == "3": 
    c.execute('SELECT AVG(score), name FROM scores WHERE classNo = (?)', (classNo,))   

row = c.fetchall() 
row = ', '.join(map(str, row)) 
print(row) 

myFile.commit() 
myFile.close() 

回答

1

您需要添加一個GROUP BY聲明。 sql中的聚合函數通常在GROUP BY中非常有用。

SELECT MAX(score), name FROM scores WHERE classNo = (?) GROUP BY name 
+0

謝謝,這工作完美 – jburke424