2017-10-19 110 views
1

我有一个比赛中的球员列表。如何在PSQL中查询表以便它返回与成对相同的列表?

tournament=> SELECT * FROM players; 
     name  | player_id 
-------------------+----------- 
Twilight Sparkle |   9 
Fluttershy  |  10 
Applejack   |  11 
Pinkie Pie  |  12 
Rarity   |  13 
Rainbow Dash  |  14 
Princess Celestia |  15 
Princess Luna  |  16 
(8 rows) 

这就是我希望列表看起来如何。我如何让postgreSQL使它成为如此?

 name1  | id1 |  name2  | id2 
-------------------+---------+-------------------+------- 
Twilight Sparkle | 9 | Fluttershy  | 10 
Applejack   | 11 | Pinkie Pie  | 12 
Rarity    | 13 | Rainbow Dash  | 14 
Princess Celestia | 15 | Princess Luna | 16 
(4 pairs) 
+0

我使用Pythons itertools计算了这一点。 –

回答

0

解决!不幸的是,我找不到用简单的SQL查询来做到这一点的方法。但是,感谢StackOverFlow here上的一个线程,我能够使用Python的itertools找到一个解决方案。现在它返回4对而不是28个。我已经通过了所有10个测试!下面是我对tournament.py的补充:

import itertools 

swissPairings(): 

    standings = playerStandings() 

    pairingsiterator = itertools.izip(*[iter(standings)]*2) 
    # Iterate through the list and build the pairings 
    results = [] 
    pairings = list(pairingsiterator) 
    for pair in pairings: 
     id1 = pair[0][0] 
     name1 = pair[0][1] 
     id2 = pair[1][0] 
     name2 = pair[1][1] 
     matchup = (id1, name1, id2, name2) 
     results.append(matchup) 
    return results 
+0

它被称为“数据透视”或“交叉表”,在应用程序中确实做得更好。 SQL并不适合这个。 –

相关问题