SQL选择多个MAX和MIN - Python

时间:2015-04-26 14:50:22

标签: python sql database sqlite

我有一个程序,可以在数据库中存储学生的分数。我想为每个学生选择最高分。目前,只返回所有学生中得分最高的一名学生,而不是每名学生的最高分。任何人都可以帮我解决这个问题吗? (仅供参考,其中有一个"得分"列,其中包含存储的分数列表)

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 个答案:

答案 0 :(得分:1)

您需要添加GROUP BY语句。 sql中的聚合函数通常对GROUP BY最有用。

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