0

If I have a query like this

SELECT * FROM table1

I get a result something like this:

enter image description here

How can I write a query from the same table that returns me something like this:

enter image description here

value_name has to turn into columns and the value column has to turn into its values.

Also notice that the ids are repeated and its description is always the same one.

I'm working with PostgresQL

1
  • This is much easier to do in the application than in SQL. Commented Jan 9, 2021 at 20:00

1 Answer 1

2

If you know the values in advance, you can use conditional aggregation:

select id, description,
       max(value) filter (where value_name = 'FE') as fe,
       max(value) filter (where value_name = 'H2O') as h2o,
       max(value) filter (where value_name = 'N') as n
from t
group by id, description;

If you don't know the names, then you cannot accomplish this with a single SQL query. You need to use dynamic SQL or use an alternate data representation such as JSON.

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.