This is another common sql server interview question. We will be using the following Countries table in this example.
![transpose rows to columns sql](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEj7q1oINcWa52p0t_gCukf7FSzShV-Mwi4qh85heaeVcs8-dcL7NCxuDH0bqEDIqT1b9jh9xfmHyn-9z53o7STFWSD9fAl-mUBV8h_enbuXIj5uDMvV4krB8t7wc5ZrefPaBtwJyN_Eq_uI/s1600/transpose+rows+to+columns+sql.png)
SQL to create the table
Create Table Countries
(
Country nvarchar(50),
City nvarchar(50)
)
GO
Insert into Countries values ('USA','New York')
Insert into Countries values ('USA','Houston')
Insert into Countries values ('USA','Dallas')
Insert into Countries values ('India','Hyderabad')
Insert into Countries values ('India','Bangalore')
Insert into Countries values ('India','New Delhi')
Insert into Countries values ('UK','London')
Insert into Countries values ('UK','Birmingham')
Insert into Countries values ('UK','Manchester')
Here is the interview question:
Write a sql query to transpose rows to columns. The output should be as shown below.
![transform rows to columns sql](https://blogger.googleusercontent.com/img/b/R29vZ2xl/AVvXsEgsd-FnJKtTiBOhpf7A8e-X8IARtrpOvsTJgYjoeCzEiTFQfu9GgOov1sOdLe753s2n9RG68B1-820rHJmgndJwQVdAGspSZsUupzzZSGQIkTblXYxo21ijWGHROLlrTKmvfnlnDfGJS1Vi/s1600/transform+rows+to+columns+sql.png)
Using PIVOT operator we can very easily transform rows to columns
Select Country, City1, City2, City3
From
(
Select Country, City,
'City'+
cast(row_number() over(partition by Country order by Country)
as varchar(10)) ColumnSequence
from Countries
) Temp
pivot
(
max(City)
for ColumnSequence in (City1, City2, City3)
) Piv
0 comments:
Post a Comment
Note: only a member of this blog may post a comment.