Eduardo Tricio Eduardo Tricio -4 years ago 89
Python Question

After the second calling of my function I get the following error: more than one row returned by a subquery used as an expression

This is the definition of my playerStandings() function:

def playerStandings():
"""Returns a list of the players and their win records, sorted by wins.

The first entry in the list should be the player in first place, or a player
tied for first place if there is currently a tie.

Returns:
A list of tuples, each of which contains (id, name, wins, matches):
id: the player's unique id (assigned by the database)
name: the player's full name (as registered)
wins: the number of matches the player has won
matches: the number of matches the player has played
"""
db = connect()
c = db.cursor()
c.execute("select players.id,players.name, count((select matches.winner from matches where matches.winner = players.id))as win, count((matches.winner))as matches from players left join matches on players.id = matches.winner or players.id = matches.loser group by players.id order by win desc,id")
standing = c.fetchall()
db.close()
return standing


The first time I call upon this function the program runs fine, the problem is when I try to print my standings a second time. The following is my main function.

standings = playerStandings()
print playerStandings()
[id1,id2,id3,id4,id5,id6] = [row[0] for row in standings]
reportMatch(id2,id1)
reportMatch(id4,id3)
reportMatch(id5,id6)
print playerStandings()
print swissPairings()
reportMatch(id2,id4)
reportMatch(id1,id5)
reportMatch(id6,id3)
print playerStandings()
print swissPairings()

Answer Source

Don't put a SELECT inside COUNT(). Use SUM() to count the rows that match an additional criteria.

SELECT p.id, p.name, SUM(CASE WHEN m.winner = p.id THEN 1 ELSE 0 END) AS win, COUNT(m.winner) AS matches
FROM players as p
LEFT JOIN matches AS m ON p.id IN (m.winner, m.loser)
GROUP BY p.id
ORDER BY win DESC, p.id
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download