0

I have a data in the following format :

ID          Vendor Name     Company Name

1                 VendorA         CompanyA

2                 VendorB         CompanyB

3                 VendorC         CompanyC

I want in the following format

ID                                     CompanyDetails     
1                                          CompanyA                                

1                                          VendorA                               

2                                          CompanyB

2                                          VendorB 

3                                          CompanyC

3                                           Vendor C

i have used Union all but did not work , please help me write an sql script for this

thank you

5 Answers 5

1
SELECT ID,    CompanyDetails
FROM
(
    SELECT ID, VendorName As CompanyDetails, 2 as Tag
    FROM tableName
    UNION ALL
    SELECT ID, CompanyName, 1 As Tag
    FROM tableName
) Z
ORDER BY ID, Tag
Sign up to request clarification or add additional context in comments.

3 Comments

i had tried this but Union all alters the sequence. i print Compoany Name then Vendor Name for some rows and reverse the sequence for some other rows
Check edited answer , the Tag column used in ORDER By will cxause Comapy Name to come first and then VendorName for each ID
For what rows you want sequence changed ? Specify what dou mean
0

Try this

SELECT ID, [Vendor Name] from table
union all
SELECT ID, [Company Name] from table
Order by ID

Comments

0

Try this it will help you

select * into #tab from(
select 1 ID, 'VendorA' as [Vendor Name], 'CompanyA' [CompanyName]
union all
select 2, 'VendorB', 'CompanyB'
union all
select 3, 'VendorC', 'CompanyC'
)as a


select id,[Vendor Name] from #tab
union all
select id,[CompanyName] from #tab
order by  ID

Comments

0

You can set an Order to keep the sequence.

SELECT ID, CompanyDetails
FROM (
    SELECT ID, CompanyName AS CompanyDetails, 1 AS Ord
    FROM #table
    UNION
    SELECT ID, VendorName, 2 AS Ord
    FROM #table


) A
ORDER BY ID, Ord

Comments

0

By using cross apply and NTile also we can achieve

 Select ID,CompanyDetails 
        from (
Select NTILE(6)OVER(PARTITION BY COL ORDER BY COL DESC )ID ,
T.VAL As CompanyDetails 
            from (
select COL,VAL from  #Table1
CROSS APPLY(VALUES 
    ('Vendorname',[Vendor Name]),
    ('CompanyName',[CompanyName]))CS(COL,VAL))T)TT
    ORDER BY ID

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.