title: SQL Server - join rows into comma separated list
body: <p>Let's suppose I have a temporary table which looks like this:</p>
  
  <pre><code>+----+------+
  | Id | Value|
  +----+------+    
  | 1  |   1  |
  | 1  |   2  |
  | 1  |   3  |
  | 2  |   1  |
  | 2  |   2  |
  +----+------+
  </code></pre>
  
  <p>And I want my table to be like this:</p>
  
  <pre><code>    +----+----------+
      | Id | ValueList|
      +----+----------+    
      | 1  |   1,2,3  |
      | 2  |   1,2    | 
      +----+----------+
  </code></pre>
  
  <p>So basically I need to group my values as a comma separated list.
  I already tried the following:</p>
  
  <pre><code>SELECT Id, STUFF((SELECT ',' + CAST(VALUE AS varchar) FROM @MyTable FOR XML PATH('')), 1 ,1, '') AS ValueList
  FROM @MyTable
  GROUP BY Id
  </code></pre>
  
  <p>But I get something like:</p>
  
  <pre><code>        +----+---------------------+
          | Id |      ValueList      |
          +----+---------------------+    
          | 1  |   1,1,1,1,1,1,...   |
          +----+---------------------+
  </code></pre>
  
  <p>I cant find what I am doing wrong. Could someone help with this query? Or point me to a right direction?
  Thank you.</p>