2017-03-23 23 views
0

這是我playerStandings的定義()函數:後,我的函數的第二個呼叫我收到以下錯誤:被用作表達式子查詢返回多行

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 

我第一次請求這個函數程序運行良好,問題是當我嘗試再次打印我的排名時。以下是我的主要功能。

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() 

回答

0

不要把SELECTCOUNT()。使用SUM()來計算符合附加標準的行。

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 
+0

當我嘗試這個我得到以下錯誤:psycopg2.ProgrammingError:函數sum(boolean)不存在。爲什麼會這樣呢?感謝您的答覆。 –

+0

糟糕,我誤以爲是MySQL。 – Barmar

相關問題