I stumbled on a problem  when I try to use CTE with GROUP BY.
I need to concatenate strings in a 'group by' manner, that is, from the table:
   id value
   --------
    1    a
    1    b
    2    c
    2    d
I want to get the following result:
id vals
1  a,b
2  c,d
The following query will give the desired result([How to use GROUP BY to concatenate strings in SQL Server?)
create table #B 
(
     id int, 
     value varchar(8)
);
insert into #B (id, value) 
values (1, 'a'), (1, 'b'), (2, 'c'), (2, 'd');
select 
    id, 
    stuff((select distinct ','+value 
           from #B 
           where id = a.id 
           for xml path ('')),1,1,'') as vals 
from #B as a
group by id;
But if I replace the table #B with a trivial CTE:
with A as 
(
     select * from #B
)
select 
    id, 
    stuff((select distinct ',' + value 
           from A 
           where id = a.id 
           for xml path ('')),1,1,'') as vals 
from A as a 
group by id
SQL Server returns a wrong result without any warning:
id vals
----------
1  a,b,c,d
2  a,b,c,d
Can anyone explain how the CTE query above comes up the wrong result? It is interesting to know how the CTE above is interpreted by SQL Server. Thank you.
 
     
    