Is there a way in PostgreSQL 8.4 to use table cell content as the column name in result (for example, as alias)?

StackOverflow https://stackoverflow.com/questions/17637073

Question

I have a relation one-to-many. I have three tables:

|A       |  | B                |  |C      |
|ID| ... |  |ID|A_ID|C_ID|VALUE|  |ID|NAME|
|1 |     |  |1 |1   |2   |val_1|  |1 |a   |
|2 |     |  |2 |1   |1   |val_2|  |2 |b   |
|3 |     |  |3 |2   |1   |first|  |
...

I need to get a result table:

|ID|a    |b    |
|1 |val_2|val_1|
|2 |NULL |NULL |
|3 |first|NULL |

I.e., first column is A.ID, and the others are the VALUE columns from B, but the names of these columns are NAME from the C.

One of my ideas was the query

SELECT A.ID, B.VALUE AS C.NAME FROM A, B, C WHERE B.A_ID = A.ID AND B.C_ID = C.ID

but I have:

ERROR:  syntax error at or near "."

Does anybody know how to resolve the problem with one query in PostgreSQL 8.4?

Was it helpful?

Solution

It looks like you want a "crosstab" or "pivot" query. See the tablefunc module for some functions that'll help with that, and search Stack Overflow for [postgresql] crosstab or [postgresql] pivot.

SQL does not permit you to use column-references as column-aliases like you wrote above. It's not valid syntax and there'd be some logical problems with making it work.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top