I have the following table:
Name Rating
Engineering 1
Financials 3
Scope 1
Schedule 2
Risks 3
People 3
I would like the output to be as follows:
Engineering Financials Scope Schedule Risks People
1 3 1 2 3 3
Using SQL query only. Can someone help me to get the correct output?
You are trying to
PIVOTthe data. SQL server has aPIVOTfunction that can perform this for you. To perform thePIVOTyou need to decide what aggregate function to use. In my sample, I usedMAX()but you can useSUM(), etc.If you do not have a pivot function then you can can use an aggregate function with a
CASEstatement to do this.Aggregate/CASE version: This version requires that you hard-code all of the names into the columns.
See SQL Fiddle with Demo
Static PIVOT version: You will hard code the values of the names into this query
See SQL Fiddle with Demo
The above versions work great if you have a known number of columns, but if your
namevalues are unknown, then you can use dynamic sql toPIVOTthe data.Dynamic PIVOT version:
See SQL Fiddle with Demo
All three versions will produce the same result: