Click here to Skip to main content
15,887,596 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello guys, I have some data in sql server like this -

Num Alphabet
1 A
1 B
2 C
2 D
2 E
3 F

Can you help me make an SQL query that will display the data like this -


Alpha1 Alpha2 Alpha3
A C F
B D
E


Thanks in advance. I tried some things but cannot get this exact format.
Posted
Comments
Mehdi Gholam 25-May-15 8:22am    
Why?
Frankie-C 25-May-15 8:22am    
What have you tried?
_Asif_ 25-May-15 8:27am    
This seems like a home work?
Rak_Avasthy. 26-May-15 2:34am    
No its not a homework. I have some huge data and this is just a sample data for the condition I need. I needed help coz sometimes when we are fed up with work our mind stops thinking the PIVOT may do the trick

Check this:

SQL
DECLARE @tmp TABLE (Num INT, Alphabet VARCHAR(5))

INSERT INTO @tmp (Num, Alphabet)
VALUES(1, 'A'),
(1, 'B'),
(2, 'C'),
(2, 'D'),
(2, 'E'),
(3, 'F')

SELECT Num, [1] AS Alpha1, [2] AS Alpha2, [3]  AS Alpha3
FROM (
    SELECT *, ROW_NUMBER() OVER(PARTITION BY Num ORDER BY Alphabet) AS Alpha
    FROM @tmp
    ) AS DT
PIVOT (MAX(Alphabet) FOR Alpha IN([1], [2], [3])) AS PT


Result:
Num Alpha1  Alpha2  Alpha3
1   A       B       NULL
2   C       D       E
3   F       NULL    NULL
 
Share this answer
 
Comments
Rak_Avasthy. 26-May-15 2:33am    
Thanx. That did the trick
Actually this query gave the correct result

SELECT [1] AS Alpha1, [2] AS Alpha2, [3] AS Alpha3
FROM (
SELECT *, ROW_NUMBER() OVER(PARTITION BY Num ORDER BY Alphabet) AS Alpha
FROM @tmp
) AS DT
PIVOT (MAX(Alphabet) FOR Num IN([1], [2], [3])) AS PT
Maciej Los 26-May-15 2:57am    
You're very welcome ;)
This looks like homework, so no - we won;t just give you teh solution.
Start by looking at PIVOT[^] and give it a try yourself!
 
Share this answer
 
Comments
Rak_Avasthy. 26-May-15 2:24am    
Thanx anyway

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900