Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

SQL select rows into new columns

I have a database table which looks like this:

ID         parameter          value
1          A                  1
1          B                  1002
2          A                  5
2          B                  1055

I would like to create a SQL query to receive such a table:

ID         value of parameter A            value of parameter B
1          1                               1002
2          5                               1055

How can I transform the table to create a new columns for each parameter with it corresponding value?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can combine CASE with any aggregation function (like SUM(), MAX(), etc.) to pivot the data manually.

For example:

select
  id,
  sum(case when parameter = 'A' then value end) as a,
  sum(case when parameter = 'B' then value end) as b,
  ...
  sum(case when parameter = 'Z' then value end) as z
from t
group by id
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading