JPacheco
JPacheco

Reputation: 83

How to transpose a query result in SQL Server (rows to columns)

my query gives me a result as follows:

initial query

so, i want to transform that result into this:

query transformed

Note the crossing fields with NULL values.

Upvotes: 2

Views: 33774

Answers (3)

JPacheco
JPacheco

Reputation: 83

I have found a nice solution to my problem thanks to @[P Doe], for guiding me to the solution.

The link is:

Dynamic PIVOT in Sql Server

Upvotes: 1

Javlon Ismatov
Javlon Ismatov

Reputation: 194

 select id,SN,
 case Part when 'P1' then '1' else null end 'P1',
 case Part when 'P2' then '1' else null end 'P2',
 case Part when 'P3' then '1' else null end 'P3',
 case Part when 'P4' then '1' else null end 'P4',
 case Part when 'P5' then '1' else null end 'P5'
  from table1

Upvotes: 0

Paul
Paul

Reputation: 56

PIVOT is the way to accomplish this and it can be confusing (at least it was to me) at first.

https://www.codeproject.com/Tips/500811/Simple-Way-To-Use-Pivot-In-SQL-Query

Upvotes: 2

Related Questions