To Transfer Row data to column data in sql table using pivot.
1. We need to create table like below image.
CREATE table tblCountryCity
(
Country nvarchar(50),
City nvarchar(50)
)
Insert into tblCountryCity values ("USA","New York"), ("USA","Houston"), ("USA","Dallaas")
Insert into tblCountryCity values ("India","Hydrabad"), ("India","Banglore"), ("India","New Delhi")
Insert into tblCountryCity values ("UK","London"), ("UK","Bermingham"), ("UK","Manchester")
2. After Creating table and inserting data in table. we need to execute below query.
select Country, City1 , City2, City3
from
(
Select Country,City,
'City' + CAST (ROW_NUMBER() over (Partition By Country Order by Country) as nvarchar(10)) as ColumnSequence
from tblCountryCity
)Temp
PIVOT
(
Max(City)
For ColumnSequence in (City1, City2, City3)
)PIV
Result:-
For Example
CREATE table tblCountryCity
(
Country nvarchar(50),
City nvarchar(50)
)
Insert into tblCountryCity values ("USA","New York"), ("USA","Houston"), ("USA","Dallaas")
Insert into tblCountryCity values ("India","Hydrabad"), ("India","Banglore"), ("India","New Delhi")
Insert into tblCountryCity values ("UK","London"), ("UK","Bermingham"), ("UK","Manchester")
2. After Creating table and inserting data in table. we need to execute below query.
select Country, City1 , City2, City3
from
(
Select Country,City,
'City' + CAST (ROW_NUMBER() over (Partition By Country Order by Country) as nvarchar(10)) as ColumnSequence
from tblCountryCity
)Temp
PIVOT
(
Max(City)
For ColumnSequence in (City1, City2, City3)
)PIV
Result:-