Can you SELECT the same column twice but one of them with a different alias? [Python, PostgreSQL]

时间:2017-06-15 09:25:09

标签: python sql postgresql

I'm working with this python function with the following description given (and my code below). I want to know if I can use the following column twice (`players.id, players.player_name' and 'players.id AS opponent, players.player_name AS opponent_name').

def swissPairings():
    """Returns a list of pairs of players for the next round of a match.

    Assuming that there are an even number of players registered, each player
    appears exactly once in the pairings.  Each player is paired with another
    player with an equal or nearly-equal win record, that is, a player adjacent
    to him or her in the standings.

    Returns:
      A list of tuples, each of which contains (id1, name1, id2, name2)
        id1: the first player's unique id
        name1: the first player's name
        id2: the second player's unique id
        name2: the second player's name
    """
    db = psycopg2.connect(database=DBNAME)
    c = db.cursor("SELECT players.id, players.player_name,
    players.id AS opponent, players.player_name AS opponent_name, (SELECT 
    count(matches.winner) from matches where matches.winner = 4 -
matches.loser) AS same_score
            FROM players, matches")
        c.execute()

It should look something like this (btw I just put same score for extra):

id | player_name | opponent_id | opponent_name | same_score
1  | Andrew      |   3         | Eric          |  4
2  | Samantha    |   5         | Bob           |  3
7  |
8  |

This is the SQL table I'm using:

CREATE TABLE players (
id INT PRIMARY KEY,
player_name VARCHAR
);

CREATE TABLE matches (
id INT PRIMARY KEY,
winner INT REFERENCES players(id),
loser INT REFERENCES players(id)
);

Basically, in a match(matches.id) between two people, one either gets places in winner column or loser column. It's a swiss tournamnet with no elimination so everyone will have 4 rounds of matches. Other additional information: I use Count() to get the total of wins or how many times a player.id appears in matches.winner column.

If you want me to put the whole python codes to analyse it all, please ask.

1 个答案:

答案 0 :(得分:0)

Your question body doesn't appear to actually be asking anything? Though to answer the question in your title, you can do this with column aliases:

In short:

select Col1 as Alias1
      ,Col1 as Alias2
from table