Possible Duplicate:
SQL Server dynamic PIVOT query?
Is it possible to execute a query on the following table:
Game Player Goals
----- ------ ------
Game1 John 1
Game1 Paul 0
Game1 Mark 2
Game1 Luke 1
Game2 John 3
Game2 Paul 1
Game2 Luke 1
Game3 John 0
Game3 Mark 2
which gives a result like this:
Game John Paul Mark Luke
----- ---- ---- ---- ----
Game1 1 0 2 1
Game2 3 1 - 1
Game3 0 - 2 -
It turns each distinct player into a column and groups the games gives goals per game per player.
You can use the
PIVOT
function. If you have a known number of columns, then you can hard-code the values:See SQL Fiddle with Demo
If you have an unknown number of columns, then you can use dynamic sql:
See SQL Fiddle with Demo