KAs
KAs

Reputation: 1868

convert cell value to respective column in PostgreSQL

Here's the sample:

select * from tmp

--output
A       B       Value
---------------------
a       x       1
b       x       2
a       y       3
b       y       4
c       y       5

After a SQL command grouping on B column, I'd like to make each value of column A to be a separate column as illustrated below:

B       a       b       c
----------------------------
x       1       2       null
y       3       4       5

If there any specific terminology for this transformation? Thanks!

Upvotes: 0

Views: 234

Answers (1)

Bhavesh Ghodasara
Bhavesh Ghodasara

Reputation: 2071

You need to find max of other value and group it by with anchor column(b in your case). Please note that your column count should be similar to number of values expected in field A.

select b,
max(case when A='a' then Value else null end)a,
max(case when A='b' then Value else null end)b,
max(case when A='c' then Value else null end)c
from tmp
group by 1

Upvotes: 1

Related Questions