Display data columns to rows using Sql Server

Dear Expert

how to display n number of columns to rows using Sql Server. I do not know the defined columns its vary based on requirements

A   01
B   02
C   03
...   ...
N   N

Result should be
A     B     .............N
01   02   .............N
LVL 22
Tapan PattanaikSenior EngineerAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Ankit PareekOnline MarketingCommented:
Hey you can easily do this just need to use following code to change data columns to rows just see the below code and use it
select 01,02,03,..N
from
(
  select value, columnname
  from yourtable
) d
pivot
(
  max(value)
  for columnname in (01, 02, 03,.. N)
) piv;

Open in new window

0
PortletPaulfreelancerCommented:
assumption: The data in column1 is unique (distinct)

To arrive at headings which reflect the data requires 'dynamic sql" (sql that is used to create more sql)

This result:
| [A] | [B] | [C] | [...] | [N] |
|-----|-----|-----|-------|-----|
|  01 |  02 |  03 |   ... |   N |

Open in new window


was produced from this query, which builds the required sql then executes that:
DECLARE @cols  AS NVARCHAR(MAX),
        @query AS NVARCHAR(MAX)

SET @cols = STUFF((SELECT ', max(case when col1 = ''' + col1 + ''' then col2 end) as ''' + quotename(col1) + ''''
            FROM table1 h
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT ' + @cols + ' from table1'

execute(@query)

Open in new window


Note the approach I have chosen to use does not use the "pivot feature" of T-SQL, I just find this the easier way.

also see:
Dynamic Pivot Procedure for SQL Server

http://www.experts-exchange.com/Microsoft/Development/MS-SQL-Server/SQL_Server_2008/Q_28188971.html#a39338027

and see  demo at: http://sqlfiddle.com/#!6/02b2f/1
    CREATE TABLE Table1
        ([col1] varchar(30), [col2] varchar(30))
    ;
        
    INSERT INTO Table1
        ([col1], [col2])
    VALUES
        ('A', '01'),
        ('B', '02'),
        ('C', '03'),
        ('...', '...'),
        ('N', 'N')
    ;
    
**Query 1**:

    DECLARE @cols  AS NVARCHAR(MAX),
            @query AS NVARCHAR(MAX)
    
    SET @cols = STUFF((SELECT ', max(case when col1 = ''' + col1 + ''' then col2 end) as ''' + quotename(col1) + ''''
                FROM table1 h
                FOR XML PATH(''), TYPE
                ).value('.', 'NVARCHAR(MAX)') 
            ,1,1,'')
    
    set @query = 'SELECT ' + @cols + ' from table1'
    
    execute(@query)
    

**[Results][2]**:
    | [A] | [B] | [C] | [...] | [N] |
    |-----|-----|-----|-------|-----|
    |  01 |  02 |  03 |   ... |   N |

  [1]: http://sqlfiddle.com/#!6/02b2f/1

Open in new window

0
Tapan PattanaikSenior EngineerAuthor Commented:
Hi Paul Maxwell,

thanx for your solution but i need one more help

result should come
| A | B| C | ... | N |           header
|-----|-----|-----|-------|-----|
| A | B | C | ... | N |           row1 (header data should display as row )
|  01 |  02 |  03 |   ... |   N |           row2
0
PortletPaulfreelancerCommented:
That is more difficult, are you absolutely certain you REALLY NEED the column headings to be equal to the data?
0
PortletPaulfreelancerCommented:
Here is one approach that works... but don't complain about the efficiency please:

DECLARE
      @cols1  AS NVARCHAR(MAX)
    , @cols2  AS NVARCHAR(MAX)
    , @query AS NVARCHAR(MAX)

SET @cols1 = STUFF((SELECT ', max(case when col1 = ''' + col1 + ''' then col1 end) as ''' + quotename(col1) + ''''
            FROM table1 h
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

SET @cols2 = STUFF((SELECT ', max(case when col1 = ''' + col1 + ''' then col2 end) as ''' + quotename(col1) + ''''
            FROM table1 h
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query =   'SELECT ' + @cols1 + ' from table1'
             + ' UNION ALL'
             + ' SELECT ' + @cols2 + ' from table1'
--select @query
execute(@query)

Open in new window


NOTE

there are extra issues now, the data type of the columns - if not identical - will cause issues with the union
1

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Microsoft SQL Server 2008

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.