Home > other >  find a way to reorganize sql table
find a way to reorganize sql table

Time:09-11

I am working on a table like below:

class parameter value
A name John
A city NY
A year 2022
B name ANNA
B city NM
B year 2021

I want to save it in new table like this:

class name city year
A John NY 2022
B ANNA NM 2021

CodePudding user response:

Here is a solution with Sql Server using pivot.

select *
from   t
pivot (max(value) for parameter in([name], [city], [year]))  pvt
class name city year
A John NY 2022
B ANNA NM 2021

Fiddle

CodePudding user response:

Here's a solution with Postgres using crosstab

select *
from crosstab(
  'select class, parameter, value
   from t')
as t(class text, name text, city text, year text);
class name city year
A John NY 2022
B ANNA NM 2021

Fiddle

  •  Tags:  
  • sql
  • Related