1

I have the following table:

column_name | a | b
--------------------
     a      | 0 | 1 
--------------------
     b      | 2 | 3

Is it possible to write a select statement that will return:

result
------
   0
   3

(I want to pick a column depending on the name specified in column_name)

The trick is that I do not know how many columns will I have and what will be their names (except for the column_name column)

I can't create temporary tables, functions and so on. Yes, it's a part of a task on a SQL course on my university, still not the task itself, so I believe I can ask for help here.

2
  • 1
    I am sure, the SQL course provides the question more clearly ... Commented May 27, 2015 at 0:08
  • You'd need dynamic SQL. Read up on PL/PgSQL's EXECUTE command. Or maybe you are looking for crosstabulation / pivot, in which case you want the crosstab function from the tablefunc extension. Commented May 27, 2015 at 5:54

2 Answers 2

1
select case when column_name='b' then b else a end
from ...

basically? it'd get incredibly ugly tedious for more than just a couple columns

Sign up to request clarification or add additional context in comments.

2 Comments

I forgot to specify that this was just an example and that I do not know the number of columns nor their names in that task. I updated the question so it says it now.
then you'll have to use dynamic sql. e.g. select column_name, then build a new sql string to select value_retrieved_from_other_query and execute that statement. you cannot use "values" from one part of a query as sql keywords or field/table names elsewhere in the same query.
0

You can use postgresql json data type (and its related features):

select row_to_json(table_name)->>(row_to_json(table_name)->>'column_name') from table_name;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.