title: Comma Separated list of rows of a column with group by on other columns
body: <p>Below is the structure of table I have: -</p>
  
  <p>Table <strong>T1</strong></p>
  
  <pre><code>C1  C2  C3
  ---------- 
  X   P   A
  X   P   B
  Y   Q   C
  Y   Q   D
  </code></pre>
  
  <p>Desired output: - </p>
  
  <pre><code>C1   C2   C3
  ------------ 
  X    P    A,B
  Y    Q    C,D
  </code></pre>
  
  <p>Note: - I know i can do the same with <code>For XML('')</code> with group by on C1 and C2, but the main problem in my case is that the table T1 here must be a physical table object (either permanent or temp or table var or CTE) in DB. But in my case it's a derived table and when i am using the below query it's saying invalid object.
  In my case it's not good to replace the derived table with temp# tables or fixed tables or even with CTE or table variable because it will take a great effort.</p>
  
  <pre><code>SELECT 
  b.C1, b.C2, Stuff((',' + a.C3 from t1 a where a.c1 = b.c1 for XML PATH('')),1,1,'') FROM
  T1 b group by b.c1,b.c2
  </code></pre>
  
  <p>I did not have T1 as fixed table. Please consider it as derived table only.</p>
  
  <p>I need the solution with existing derived table.
  Please help.</p>
  
  <p>Below is the query with derived table: - 
  Please consider this only as a demo query. It's not as simple as given below and a lot of calculations have done to get the derived tables and 4 levels of derived tables have been used.</p>
  
  <pre><code>SELECT C1, C2, Stuff((',' + a.C3 from A B where a.c1 = b.c1 for XML PATH('')),1,1,'')
  FROM
  (
  SELECT C1, C2, C3  FROM T1 WHERE C1 IS NOT NULL--and a lot of calculation also
  )A
  </code></pre>
  
  <p>Please mind that T1 is not just below one step, in my case T1 the actual physical table is 4 level downs by derived tables.</p>