turn the distinct value of columns into a rows pos

2019-03-04 16:57发布

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?

1条回答
等我变得足够好
2楼-- · 2019-03-04 17:32

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.

查看更多
登录 后发表回答