Given this data:
Name Property Value
---------- ---------- ----------
Bob Hair Red
Bob Eyes Blue
Fred Hair Brown
Fred Height Tall
what SQL would be required to produce these results?
Property Bob Fred
---------- ---------- ----------
Hair Red Brown
Eyes Blue
Height Tall
I’m using SQL Server 2008, but a generic solution would be nice.
You did not specify what RDBMS you are using but this is a pivot. You can use an aggregate function and a
CASEexpression in all databases:See SQL Fiddle with Demo
If you are using a database that has a
PIVOTfunction (SQL Server 2005+/Oracle 11g+), then your code will be similar to this:See SQL Fiddle with Demo
The above queries work great, if you know the name values ahead of time, but if you don’t then you will want to use dynamic sql:
See SQL Fiddle with Demo
All three will produce the same result: