Click here to Skip to main content
15,893,487 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I have a table with only one column about 100 rows of only names. But I need to display the 3 names in a row. So that I will get 34 rows each row with 3 names.

VB
Example:

Name
_____

Raj
Sam
Guru
Tej
Avin
Sami
Fanst




I need to display above data as

Name Name1 Name2
____ _____ ______
Raj  Sam    Guru
Tej  Avin   Sami
Fanst


No condition just need to covert single column value into 3 columns data. But only thing is need to order by primary key value.
Posted

This solution is quite generic.
It works with gaps in your primary key as well as being very easy to change the number of columns in the query.
Manchanx solution should be faster though.
SQL
WITH ordered AS (
    SELECT  name
           ,Row_Number() OVER (ORDER BY name) -1 AS rn --change the order by to your PK
    from    table1
    )
,modded as (    
    select  name
           ,Mod(rn,3) m    -- 3 is the number of columns
           ,Floor(rn/3) r  -- 3 is the number of columns

    from    ordered
    )
SELECT  *
FROM    modded
pivot   (
    Max(name)
    for m
    IN (0 as name,1 as name1,2 as name2)
    )
ORDER BY r
 
Share this answer
 
v2
Comments
Maciej Los 18-Mar-15 8:45am    
+5
Disclaimer: The following would work for Sql-Server. I assume it will work for Oracle too but I can't guarantee.

Assuming your primary key is a single integer column starting at 1 and incrementing continuously (1, 2, 3, ...):

SQL
SELECT t1.Name Name1,
       t2.Name Name2,
       t3.Name Name3
FROM TableName t1
LEFT JOIN TableName t2 ON t1.PK + 1 = t2.PK
LEFT JOIN TableName t3 ON t1.PK + 2 = t3.PK
WHERE Mod(t1.PK - 1, 3) = 0;


Edit: Adjustments for Oracle-compatibility, as suggested below by Jörgen Andersson
 
Share this answer
 
v2
Comments
Jörgen Andersson 18-Mar-15 8:19am    
Drop the square brackets, they're SQL Server specific and not even necessary in most cases.
WHERE (t1.PK - 1) % 3 = 0; would be WHERE Mod(t1.PK - 1,3) = 0; in Oracle
[no name] 18-Mar-15 8:20am    
Thank you!
Jörgen Andersson 18-Mar-15 8:24am    
No problems

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