I want to make my MS SQL 2008 select query display results in a very unique way that i hope somebody can help me accomplish.
Instead of having the results for 3 columns being displayed over 9 rows, i would like the data displayed in one row and have the 3 column names repeated 9 times.
I tried to Google this but i can’t seem to find the right ideas anywhere.
Thanks a million to anyone that can help!
i wanted to post up pic’s but i need rep points to do it which is so stupid! but any way i found a similar post that was answered for PostgreSQL 8.3. but i’m a total beginner so i don’t understand how to translate is for MS SQL.
before:
col1 | col2 | col3 |
-----|--------|---------|
a |12/01/12| 13/01/12|
-----|--------|---------|
b |14/01/12| 14/01/12|
after:
col1 | col2 | col3 |col1 | col2 | col3 |
-----|--------|---------|-----|--------|---------|
a |12/01/12| 13/01/12| b |14/01/12| 15/01/12|
-----|--------|---------|-----|--------|---------|
here’s the link to give you a better idea of my situation
Convert multiple rows into one row with multiple columns
In SQL Server 2005+ you can use the
PIVOTfunction to perform this. A pivot takes your values from rows and converts it into columns.There are a few ways that you can pivot the data. If you know all of the values ahead of time, then you can hard-code you query. Otherwise you could use dynamic SQL to generate the query at run-time.
A static version of a pivot would be similar to this:
See SQL Fiddle with Demo.
If you have an unknown number of values, then you would generate dynamic SQL similar to this:
See SQL Fiddle with Demo
These are taking the
col2row values from your table and turning them into columns. The result for both is the same:Prior to SQL Server 2005 or in databases that do not have a pivot function, then you would use an aggregate function with a
caseexpression to transform the data:See SQL Fiddle with Demo
One another way to do this if you want to repeat the columns, over and over again is to use the
UNPIVOTandPIVOTfunction together to get the result. If you have the sample data:And you want to repeat the
id,nameandtypevalues in repeating columns, then you can use:See SQL Fiddle with Demo. The result of this will be:
Edit #2, seeing your sample data you could use the following:
See SQL Fiddle with Demo
Gives the result: