Support us .Net Basics C# SQL ASP.NET Aarvi MVC Slides C# Programs Subscribe Download

Part 6 - Transform rows into columns in sql server

Suggested Videos:
Part 3 - How does a recursive CTE work
Part 4 - Delete duplicate rows in sql
Part 5 - SQL query to find employees hired in last n months



This is another common sql server interview question. We will be using the following Countries table in this example.
transpose rows to columns sql



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

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

sql server interview questions and answers

3 comments:

  1. its too good for transposing row to column

    ReplyDelete
  2. is it easier like below

    select
    country,
    max(case when rnk=1 then city end) over (partition by country) city_1,
    max(case when rnk=2 then city end) over (partition by country) city_2,
    max(case when rnk=3 then city end) over (partition by country) city_3
    FROM
    (
    select
    country,
    city,
    rank() over (partition by country order by city ) rnk
    FROM Countries
    ) abc

    ReplyDelete
    Replies
    1. select distinct
      country,
      max(case when rnk=1 then city end) over (partition by country) city_1,
      max(case when rnk=2 then city end) over (partition by country) city_2,
      max(case when rnk=3 then city end) over (partition by country) city_3
      FROM
      (
      select
      country,
      city,
      rank() over (partition by country order by city ) rnk
      FROM Countries
      ) abc

      Delete

It would be great if you can help share these free resources