Ricky Moreno
Ricky Moreno

Reputation: 209

Can I alias multiple columns? How?

I'm using pyodbc and postgres.

Can I alias multiple columns?

Here's the description of my problem:

Data structure:

data
id | c1  | c2
-------------
1  | 11  | 12
2  | 21  | 22

Notation: c is for column

dictionary
id | key | value
----------------
1  | k1  | v11
1  | k2  | v12
2  | k1  | v21
2  | k2  | v22

Notation: k is for key, v is for value

You can think of k1 and k2 as two more columns. The data structure is this way because it's constantly changing. I didn't design it, I just have to go with it.

I can't figure out an sql query to give me something like the following (most importantly, for some row, I can access k1 and k2 columns by some name):

data
id | c1  | c2  | k1  | k2
-------------------------
1  | 11  | 12  | v11 | v12
2  | 21  | 22  | v21 | v22

The problem I keep running into is if I alias the tables, then the sql result will contain two "key" columns from the dictionary table, meaning I can't control which column I access of the two, but if I alias the rows, then I can't control which tables are being referenced inside the sql statement.

The fix I'm thinking is to alias two columns:

SELECT * FROM data
FULL JOIN dictionary AS a1,a2,a3
ON data.id = a1
FULL JOIN dictionary AS a4,a5,a6
ON data.id = a4
WHERE a2 = k1 and a5 = k2

Notation: a is for alias

The result of this would theoretically look like

data
id | c1  | c2  | a3  | a6 
------------------------- 
1  | 11  | 12  | v11 | v12
2  | 21  | 22  | v21 | v22

Note all a's would technically be here, but 3 and 6 are the ones I'm interested in

Upvotes: 2

Views: 15101

Answers (1)

Andomar
Andomar

Reputation: 238176

You can alias the entire table, for example dictionary as d1. Then refer to the column names in that table as d1.col1. For example:

SELECT  d.id
,       d.c1
,       d.c2
,       d1.value as a3
,       d2.value as a6
FROM    data as d
LEFT JOIN
        dictionary as d1
ON      data.id = d1.id
        and d1.key = 'k1'
LEFT JOIN
        dictionary as d2
ON      data.id = d2.id
        and d2.key = 'k2'

Upvotes: 2

Related Questions