我正在尝试编写一个程序来查询数据库。该数据库是golfDB,它由一个名为players
的表组成,包含5个字段:
name
(玩家姓名)totalGross
(每轮总分的总和)totalRounds
(播放次数)pars
(制作的总数)birdies
(小鸟总数)我的程序需要输出具有最多分数的玩家,输入的玩家的平均分数(totalGross / totalRounds),并按总总分,从最低到最高的顺序列出玩家。
我真的不确定如何输出最多的播放器。现在我的代码输出了一个列表列表,每个列表都有一个播放器和它们的分区。我不确定如何通过他们的口令对它们进行排序,然后选择最高的那些,因为我尝试过的只是选择数字然后我无法回到他们属于哪个球员。
有没有人知道如何仅通过分数来订购列表列表然后它可以打印播放器?
import sqlite3
def getDBCursor(DB):
"""obtain and return a cursor for the database DB"""
conn= sqlite3.connect('/Users/tinydancer9454/Documents/python/golfDB')
cursor= conn.cursor()
return cursor
def queryDBpars(cursor):
"""find out which player had the most pars"""
cursor.execute('select name, pars from players where pars >= 0')
playerPars= cursor.fetchall()
def queryDBavgScore(cursor):
"""find the average score of inputed player"""
player= input("Please enter the player's name: ")
cursor.execute('select totalGross from players where name = ?', (player,))
totalGrossScore = cursor.fetchone()
cursor.execute('select totalRounds from players where name = ?', (player,))
totalRoundsScore = cursor.fetchone()
answer = totalGrossScore[0]/ totalRoundsScore[0]
print('The average score for', player, 'is', answer,)
def queryDBplayers(cursor):
"""lists the players in order of their total gross score"""
def main():
"""obtain cursor and query the database: golfDB"""
cursor= getDBCursor('golfDB')
queryDBpars(cursor)
queryDBavgScore(cursor)
queryDBplayers(cursor)
cursor.close()
这是输出:
[('Ruth', 16), ('Elena', 12), ('Jane', 12), ('Ezgi', 13), ('Ricki', 9), ('Margaret', 10), ('Rosalia', 16), ('Betty', 14)]
答案 0 :(得分:1)
这是一个简单的SQL问题。对于问题的直接答案,您只需要:
SELECT name, pars FROM players WHERE pars >= 0 ORDER BY pars DESC
但是这仍然让你选择了你不需要的所有球员。为了防止这种情况,只需添加一个LIMIT子句:
SELECT name, pars FROM players WHERE pars >= 0 ORDER BY pars DESC LIMIT 1
然后您将使用cursor.fetchone()
来获取该单行。
修改强>
你说可能有不止一个人拥有最多的人。这使得查询变得更加复杂:现在我们进入子查询:
SELECT name, pars FROM players WHERE pars >= 0 WHERE pars = (
SELECT MAX(pars) FROM players)
所以这样做是找到'pars'的最大值,然后选择具有此值的行。
答案 1 :(得分:0)
您可以在查询中使用ORDER BY SQL关键字,或者如果您想在python中使用它,可以通过以下几种方式实现:
def queryPars(cursor):
"""find out which player had the most pars"""
cursor.execute('select pars, name from players where pars >= 0')
## Note flipped order ^^^^^^^^^^^^
playerPars = cursor.fetchall()
pars, player_most_pars = max(playerPars)
# Now do something useful with it ;-)
docs描述了如何比较元组。 (基本上,通过入口进入)。如果您无法更改查询的顺序,则还可以执行player, pars = max(playerPars, key=lambda p: p[1])