简体   繁体   中英

How to split SQL table into multiple columns

i have a table like this one

==========================
ID | num   | person | name    
--------------------------
 1 | int   | int    | varchar
 2 | int   | int    | varchar
==========================

where id - int, primary key

num - int, foreign key . Just a number .

person - int, foreign key . Int name for person .

name - varchar(30)

i have to get a list of id's for each person like this (ID IS NOT OLD ID, i have to create new numbers and make a list of "num" for each person )

===============================
ID | person1 | person2 | person3    
-------------------------------
 1 | num     | num     | num
 2 | num     | num     | num
===============================

So i want to see numbered list of num for each person

I dont know how much different person are there... help pls.

Try the below query. Since you dont know the number of persons, put all of them in two variables, one for the select statement which contains alias and another for use in pivot which contains just the persons.

select @persons = @persons + '[' + A.name + '],'
from table1

select @personsalias = @persons + '[' + A.name + '] as [' + A.name + '],'
from table1

SELECT Id, 
@personsalias
FROM
(SELECT Id, num, name 
FROM table1) AS SourceTable
PIVOT
(
MAX(num)
FOR name IN (@persons)
) AS PivotTable;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM