tags:

views:

8162

answers:

4

My table has the following columns:

A  |  B  |  C  |  D  |  E  |  F

I want to displays this as follow:

MyColumn  |  MyColumn2
  A       |    B
  C       |    D
  E       |    F

As you can see i want to display the columns as pairs with a custom column name. The pairs are Column A and B, column C and D and column C and D.

+1  A: 
select A as [Col 1], B as [Col 2] from table
union all 
select C,D from table 
union all 
select E,F from table
Sam Saffron
Are there other ways to perform this? I also read something about (un)pivot? And what means all after union?
Martijn
UNION removes any duplicates (but requires a Sort step), UNION ALL preserves duplicates - if you know there are no duplicates or want duplicates use UNION ALL as it saves the SORT step
Kristen
Thnx, but what do you mean by SORT step?
Martijn
@Martijn Unpivot is probably not going to work here, its designed to work on single columns. So if you only needed A,C,E in a single column you could use UNPIVOT
Sam Saffron
Thnx, but i have 20 columns. Is there a quicker way than using 19 unions?
Martijn
@martinj, only two options I can think of are normalizing your table or doing the work on the application side. Can you explain why you need this functionality with the full context.
Sam Saffron
Unfortunately i cannot normalize. I know i can solve it in the code, but i really want to solve it with SQL. The results are stored in a dataset which is used in a reportviewer.
Martijn
A: 

This won't scale to a billion columns but...

Select A as MyColumn, B as MyColumn2 from Table
UNION
Select C as MyColumn, D as MyColumn2 from Table
UNION
Select E as MyColumn, F as MyColumn2 from Table

This query will remove the duplicates though. So say there's one record in the table

Hello | World | Hello | World | Hello | World

My select will only return

Hello | World

Sambo's will return all three...

Jason Punyon
watch out for union it is a performance problem cause is disticifies the set, prefer union all for these kind of problems
Sam Saffron
"disticifies" - what's that?!
Tony Andrews
I think me meant distinctifies. He's right too...
Jason Punyon
A: 

If I'm understanding you correctly you can do this with a union:

SELECT A as MyColumn, B as MyColumn2
UNION
SELECT C as MyColumn, D as MyColumn2
UNION
SELECT E as MyColumn, F as MyColumn2

If your datatypes aren't the same for the matching columns then you'll need to convert the datatype first, so something like:

SELECT CONVERT(VARCHAR(10), A) as MyColumn, CONVERT(VARCHAR(10), B) as MyColumn2
UNION
SELECT CONVERT(VARCHAR(10), C) as MyColumn, CONVERT(VARCHAR(10), D) as MyColumn2
UNION
SELECT CONVERT(VARCHAR(10), E) as MyColumn, CONVERT(VARCHAR(10), F) as MyColumn2
MrWiggles
A: 

In Sql Server 2005 Unpivot operator can solve your problem. Unpivot converts columns to rows in sql server 2005.

Hope it helps