Solved

Split row columns into multiple rows of one column

Posted on 2009-05-06
3
993 Views
Last Modified: 2013-11-05
I have a table which looks something like this:

User    VALUE1     VALUE2     VALUE3
------   ----------     -----------    -----------
Tom       4               5                  5
Jane      3               3                  3
Kate      5               3                  4

It's bad design, I know... but was this way before I got here and now I'd need to have a query return something like this:

User   VALUE
------   ---------
Tom      4
Tom      5
Tom      5
Jane     3
Jane     3
Jane     3
Kate     5
Kate     3
Kate     4

Is this possible in SQL Server through a SELECT statement?
0
Comment
Question by:mariec
3 Comments
 
LVL 31

Expert Comment

by:RiteshShah
ID: 24317275

select name,val1 as val from tablename

union

select name,val2 as val from tablename

union

select name,val3 as val from tablename

order by name
0
 
LVL 41

Accepted Solution

by:
ralmada earned 125 total points
ID: 24317436

Have you considered UNPIVOT?
Check this link for reference:
 
http://msdn.microsoft.com/en-us/library/ms177410.aspx

SELECT User, oldcolumn, Value 
FROM 
   (SELECT User, Value1, Value2, Value3
   FROM yourtable) p
UNPIVOT
   (Value FOR oldcolumn IN 
      (Value1, Value2, Value3)
)AS unpvt;

Open in new window

0
 

Author Closing Comment

by:mariec
ID: 31578575
This is great! I even did some basic performance tests and UNPIVOT is fastest way to get that data. Perfect! Thanks
0

Featured Post

NAS Cloud Backup Strategies

This article explains backup scenarios when using network storage. We review the so-called “3-2-1 strategy” and summarize the methods you can use to send NAS data to the cloud

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Introduction: When running hybrid database environments, you often need to query some data from a remote db of any type, while being connected to your MS SQL Server database. Problems start when you try to combine that with some "user input" pass…
In SQL Server, when rows are selected from a table, does it retrieve data in the order in which it is inserted?  Many believe this is the case. Let us try to examine for ourselves with an example. To get started, use the following script, wh…
This Micro Tutorial will give you a basic overview how to record your screen with Microsoft Expression Encoder. This program is still free and open for the public to download. This will be demonstrated using Microsoft Expression Encoder 4.

831 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question