| Introduction Hi, today I am writing a trick which I found while solving my friends problem in SQL. May be you people already aware with this trick but it’s new for me, so I am sharing it with you. Yesterday my friend asked me a problem in SQL, he wants to convert the horizontal data to vertical data, now what is horizontal and vertical data, answer is as follows: |
| Horizontal Data AndVertical Data |
| But my friend not having the data in the table instead he’s having the data in a variable as follows:ABC,ABD,ABE,BAC,BAD,BDE And then he wants to convert these values like in the following format so that he can store the values in the table as a single column:ABC ABD ABE BAC BAD BDE For that he’s planning to use a cursor or a while loop, to read the data and get the first three values except the comma and then get the desired result. So to solve his problem I used the UNION ALL clause and created the following querry. DECLARE @vSQL AS VARCHAR(1000), @vCode AS VARCHAR(1000) I think the UNION and UNION ALL operators are the best way to solve this type of problem. His problem is solved but I thought let’s suppose we are having the same situations with tables like the images I displayed above. Then how to do this, to get the solution of the same problem with tables I used the below code. /*First i created a table HzData which is having 5 columns.*/ /*Then i inserted one row in this table.*/ SELECT * FROM HzData /*Now the same problem with tables can be solved in two ways. /*First way to solve this problem.*/ /*Second way to solve this problem.*/ /*You can store this data in the temp table or in a I don’t know this is the right or the wrong way to solve this problem, but I found this topic intresting so that I posted this for you people. Please give your comments and suggestion about this post. |
|
******* |
SQL – Using "UNION ALL" to Convert Horizontal Data to Vertical Data
October 12, 2007 by Prashant Pandey

[...] ran across some good SQL articles on the Tech Ahead blog. Derived Tables ~ Horizontal/Vertical Data ~ Truncate and [...]
HOw can u convert the reverse? vertical table to horizontal?
Nice Trick! But the quotes have all been munged into left and right quotes making it hard to copy the examples.
SELECT
ID,
CASE RowID
WHEN 1 THEN ‘Year 1′
WHEN 2 THEN ‘Year 2′
END [Year],
CASE RowID
WHEN 1 THEN YEAR1_VALUE
WHEN 2 THEN YEAR2_VALUE
END [Value]
FROM YEARLY_INPUT
CROSS JOIN (SELECT 1 RowID UNION SELECT 2) c
And, while I’m at it, vertical to horizontal
SELECT
VoucherID,
SUM(CASE WHEN MONTH(CreateDate) = 1 THEN Amount ELSE 0 END) Jan,
SUM(CASE WHEN MONTH(CreateDate) = 2 THEN Amount ELSE NULL END) Feb
FROM Expense
GROUP BY VoucherID