views:

134

answers:

2

In SQL Server 2005, I have a table say tbl_Info. There I have one column say Info.

The values are as under

Name1
Age1
Sex1
Name2
Age2
Sex2
.....
.....
.....
And the row values goes on like this. My question is how to make row col transposition. The desired output will be
Name      Age        Sex

Name1      Age1      Sex1
Name2     Age2       Sex2

.....     ....     ........
.....     ....      ........

You can use a table variable or temp table.

And please don't give the solution by using assemblies. Because I already did that by using assemblies but I want a solution which I can even use in SQL Server 2000.

A: 

You want to pivot the table. Normally you want at least two columns, though (one for a key and one for a value) and you also generally need to know in advance what columns you are expecting in the results.

Joel Coehoorn
I am sorry to say, but you cannot use an aggregate function.Pivot needs a aggregate function
priyanka.sarkar
+1  A: 

The general idea is that you need another column to guarantee order -- that's typically going to be a primary key of some integer type, but to keep things simple say we just use:

CREATE TABLE foo (ord INT, col VARCHAR)

with ord just inserted as 0, 1, 2, etc.

Now the SELECT you want is:

SELECT a.col AS Name, b.col AS Age, c.col AS Sex
  FROM foo AS a
  JOIN foo AS b ON(b.ord=1+a.ord)
  JOIN foo AS c ON(c.ord=2+a.ord)
  WHERE a.ord%3=0

which will work on just about _any_thing that dares call itself "SQL";-).

For example, when the data are:

  ord   col
    0  John
    1    23
    2     M
    3  Mary
    4    21
    5     F
    6  Karl
    7    25
    8     M

the above SELECT's result is:

 Name   Age   Sex
 John    23     M
 Mary    21     F
 Karl    25     M
Alex Martelli
I cannot use any other column. There are some constraints imposed already in the database schema!Otherwise I would have definitely taken your solution.
priyanka.sarkar
If you have just one column, nothing guarantees the ordering is what you'd like it to be. If you're lucky, you may be able to find a way synthesize that ordering column you desperately need -- but a single-column table will never have any *robust, intrinsic* order (except whatever you might get by ordering on that one column, which is definitely not what you need in your case), so any such solution will be so fragile as to make it nearly useless. Good luck, you WILL need it (esp. if you have to respect a schema that totally flouts EVERY principle of relational DBs!-).
Alex Martelli