0

I have a schema like:

 [ad_id] . [name] . [valueofname]
   1 .       name .   "brian"
   1 .       age  .    "23"
   2 .       job  .    "IT"
   2 .       name .    "Jack"  

the row name contains multiple values : age , name, birthday, job, age I'd like to convert it into this:

[ad_id] .   [name]  .      [age] .      [birthday] .    [job]
         [valueofname] [valueofname] [valueofname] [valueofname]

I have done the query for each line:

select * from where name='name'
select * from where name='age'
select * from where name='job'

I saw the example SQL Server : Columns to Rows. But it's the opposite of my problem.

Do you have any suggestion for making one scalable query in term of performance?

Medone
  • 127
  • 1
  • 3
  • 11

1 Answers1

1

You can use conditional aggregation:

select ad_id,
       max(case when name = 'name' then valueofname end) as name,
       max(case when name = 'age' then valueofname end) as age,
       max(case when name = 'birthday' then valueofname end) as birthday,
       max(case when name = 'job' then valueofname end) as job
from t
group by ad_id;

In SQL Server, you can also do something similar with pivot.

Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
  • Thanks but here the problem i have a string values so the max and sum will not work – Medone Apr 12 '18 at 11:01
  • @a_horse_with_no_name what about if i have to do ae WHERE clauson the valueofname to have just type of value needed – Medone Apr 12 '18 at 17:20
  • @Medone . . . You can cast the value to whatever type you think is appropriate. The data in the database is being stored as a string. However, for retrieving the value (assuming one per `ad_id`), the above is fine. – Gordon Linoff Apr 12 '18 at 23:19
  • @a_horse_with_no_name if there is no rows returned to replace it as a NULL instead of " " how it would be ? because some names are missing from the database – Medone Apr 15 '18 at 23:32