Reputation: 237
I have a table like this below :
Would like to change the format as below on postgres :
I tried to use the case statement but did not give me desired results. Thank you in advance for the help !
EDIT
select (case when column_1='A' then column_1 else 'other' end) column_1,
(case when column_1='B' then Column_1 else 'other' end) column_2 from test_t
where id= random_value;
Each time the query returns only 2 rows and the row values in the column_1 are dynamic and not fixed.
Upvotes: 3
Views: 4655
Reputation: 23
Please refer to this link. Previously answered.
stackoverflow.com/a/10625294/1870151
SELECT
unnest(array['col1', 'col2', 'col3']) AS "Columns",
unnest(array[col1::text, col2::text, col3::text]) AS "Values"
FROM tbl;
Upvotes: 1
Reputation: 370
If the result you want to transpose always has only 2 rows, this will work regardless of the contents of those columns, as you asked:
SELECT
MAX(CASE WHEN row_number=1 THEN column_1 END) column_1,
MAX(CASE WHEN row_number=2 THEN column_1 END) column_2
FROM (SELECT column_1,
ROW_NUMBER() OVER (ORDER BY test_table.column_1)
FROM test_table) t;
column_1 | column_2
----------+----------
A | B
Upvotes: 0
Reputation: 352
Here we go...
CREATE TABLE test_table(column_1 text);
INSERT INTO test_table ('A'),('B');
SELECT * FROM test_table ;
column_1
---------
B
A
SELECT
max(case when column_1='A' THEN column_1 END) column_1,
max(case when column_1='B' THEN column_1 END) column_2
from test_table;
column_1 | column_2
----------+----------
A | B
In PostgreSQL you can do this easily with crosstab(), but in greenplum still it is not implemented
Upvotes: 1
Reputation: 2106
You didn't really provide enough information to really answer the question but this is how you convert those two rows from one column into two columns and forced into a single row.
select max(column_1) as column_1, max(column_2) as column_2
from (select case when column_1 = 'A' then column_1 else '' end as column_1,
case when column_1 = 'B' then column_1 else '' end as column_2
from table_name);
Upvotes: 0