Home > Back-end >  SQL select rows into new columns
SQL select rows into new columns

Time:08-02

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?

CodePudding user response:

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
  • Related