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?

4
  • 1
    Possible duplicate of stackoverflow.com/questions/1241178/mysql-rows-to-columns Commented Apr 12, 2018 at 10:05
  • @SandeshGupta thanks for but how can i do just a select without creating a view ?? Commented Apr 12, 2018 at 10:34
  • Are you using MySQL or SQL Server? Commented Apr 12, 2018 at 10:40
  • @GordonLinoff i am using both mysql and postgres from my app but the case here is in my postgres Commented Apr 12, 2018 at 10:57

1 Answer 1

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.

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

4 Comments

Thanks but here the problem i have a string values so the max and sum will not work
@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 . . . 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.
@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

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.