Harshit
Harshit

Reputation: 62

How to get multiple SQL columns into one column?

I have a SQL query "Select A,B,C,(A+B+C) as Total from Test" and the result isenter image description here

How to get the same result in only two columns like

enter image description here

Upvotes: 1

Views: 62

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1269503

You can "unpivot". My preferred method is apply:

Select v.name, v.value
from Test t cross apply
     (values ('A', A), ('B', B), ('C', C)) v(name, value);

The total is not in your result set, but that can also easily be added in.

Upvotes: 2

plalx
plalx

Reputation: 43718

You can unpivot using UNION ALL. I still prefer Gordon's solution though.

SELECT 'A' AS name, A AS [value] FROM Test
UNION ALL
SELECT 'B', B FROM Test
UNION ALL
SELECT 'C', C FROM Test

Upvotes: 1

Related Questions