Click here to Skip to main content
15,891,789 members
Please Sign up or sign in to vote.
4.00/5 (1 vote)
See more:
i have one single table and in that table there are three columns company1,company2,company3.

below is my table data :

SQL
Company1    Company2	Company3
ABC		
Test1	    Test3	Test5
Test2	    Test4	Test6
		
		
testing	    testing2	




and i want to combine these columns into single column with serial number like below :

SQL
SrNo    CompanyName
1       ABC		
2       Test1	    	
3       Test2	   
4       testing 
5       Test3
6       Test4
7       testing2	
8       Test5
9       Test6


any help would be appreciated.

thanks in advance.
Posted
Updated 18-Jan-16 1:08am
v2
Comments
Herman<T>.Instance 18-Jan-16 4:50am    
UNPIVOT
ketan chandpa 18-Jan-16 4:52am    
thanks for your comment but it would be great if you provide any example so i understand the concept.
Herman<T>.Instance 18-Jan-16 5:00am    
see here
ketan chandpa 18-Jan-16 5:06am    
i use unpivot but it gives me one columns with 18 rows.
the results also included the empty data from the table and i dont want that.
so any other help or example you have?.
ketan chandpa 18-Jan-16 5:27am    
Thanks for comments but i solve this issue in another way using union and i got the result what i want but there is only one problem that is the Serial number of the rows are repeat like 1,2,3,2,3,2,3,6,6 and i want this in serial number like 1,2,3,4,5,6 ....
any idea you have?

As you found out in the comments, UNION is much easier than UNPIVOT

For example:
SQL
SELECT SrNo, Field1
FROM table1
UNION 
SELECT SrNo, Field2
FROM table1
...


UNION ALL will give you duplicates and UNION will give you unique SrNo, field combinations.
 
Share this answer
 
You need to select the company1 .. company3 in three separate queries and concatenate those using UNION. then you need to generate a new sequence number using your existing sequence number. To keep the rows in order so company1 records come first and company3 records come last you need to add one more identifier for precedence. Then you feed both to ROW_NUMBER() and you are done.
SQL
WITH cte AS
(
    SELECT 1 AS SrNrGroup, SrNr, Company1 AS Company FROM yourtable WHERE Company1 IS NOT NULL
    UNION ALL
    SELECT 2 AS SrNrGroup, SrNr, Company2 FROM yourtable WHERE Company2 IS NOT NULL
    UNION ALL
    SELECT 3 AS SrNrGroup, SrNr, Company3 FROM yourtable WHERE Company3 IS NOT NULL
)
SELECT ROW_NUMBER() OVER(ORDER BY SrNrGroup, SrNr) AS SrNr, Company FROM cte
 
Share this answer
 
Comments
ketan chandpa 19-Jan-16 0:13am    
Thanks for your replay and your solution working well i have to change one small thing that is instead of Company1 IS NOT NULL i have to use Company1 != ''
but thanks for your help.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900