In Sql Server 2008 how can I go from here:
Owner Animal Age Height Weight
----- ------ --- ------ ------
Steve Dog 8 22 60
Steve Cat 5 11 14
Steve Gerbil 2 1.5 0.3
To here:
Owner Dog_Age Dog_Height Dog_Weight Cat_Age Cat_Height ...
----- ------- ---------- ---------- ------- ---------- ...
Steve 8 22 60 5 11 ...
So I am pivoting the Animal column, but want to generate columns for all possible combinations of animals and certain columns. No aggregate function is actually being performed. Since for my table the total number of possible combinations will be fairly large, I’d like a solution that avoids me having to explicity type out every resulting column name, but I’ll do it if I must.
I have looked at several examples of the PIVOT command, but I have not run across any that create columns from combinations like above, so I’m not sure this is possible. SQL Server is not my area of expertise.
If you don’t care about order of columns in the final output:
If column order matters (order by animal name then age/height/weight alphabetically), then you can put the columns in a table instead and generate the SQL with slightly more work:
Can’t really think of any way to do this without dynamic SQL.