Reputation: 62
I have a SQL query "Select A,B,C,(A+B+C) as Total from Test" and the result is
How to get the same result in only two columns like
Upvotes: 1
Views: 62
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
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