suresh
suresh

Reputation: 23

How to convert Rows to Columns in postgresql query

I have a simple query output of two rows and single column

Virginia
Texas

I want the output as

Virginia   |  Texas

I just tried it as two subqueries in column list.

select 
(select state from table where code='VA') as state1
(select state from table where code='TX') as state2
from tablename

Is there better way to get the result

Upvotes: 2

Views: 148

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1271151

Are you looking for string aggregation?

select string_agg(state, ' | ' order by code desc)
from table
where code in ('VA', 'TX')

You can use conditional aggregation:

select max(state) filter (where code = 'VA'),
       max(state) filter (where code = 'TX')       
from t
where code in ('VA', 'TX')

Upvotes: 1

Related Questions