title: Pivot with an indefinite amount of distinct values
body: <p>I have written this query:</p>
  
  <pre><code>SELECT s, [1] AS a1, [2] AS a2, [3] AS a3, [4] AS a4
  FROM (SELECT grade, aid, s FROM m) p
  PIVOT
  (
  SUM(grade)
  FOR aid IN ([1], [2], [3], [4])
  ) AS pvt ORDER BY pvt.s;
  </code></pre>
  
  <p>That returns the result:</p>
  
  <pre><code>s  a1  a2  a3  a4
  1  25  69  95  56
  2  27  99  16  87
  . . . .
  99 98  12  34  76
  </code></pre>
  
  <p>Which is exactly the result I want. My problem is that there will not always be four distinct values in 'aid'. Is it possible to rewrite this query (or use a stored procedure) so that the amount of 'a*' columns depends on how many distinct values are in 'aid'?</p>