Search code examples
sqlpostgresqltransposeunpivot

How to convert column heading to column values and its values in another column in postgresql


I have a table like this say the table name is online-websites and the values it has is the number of times I used it.

Amazon Flipkart Myntra
5 4 3

I want to convert it to following format

Website name Count
Amazon 5
Flipkart 4
Myntra 3.

How can I achieve this?

Thanks in Advance!


Solution

  • for your specific example one common way to unpivot is to lateral-join to a values-table construct:

    select p.*
    from t,
    lateral (
      values
      ('Amazon', t.Amazon),
      ('Flipkart', t.Flipkart),
      ('Myntra', t.Myntra)
    )p(SiteName, count)
    order by count desc;