与“group by”一起使用的SQL Server CTE导致错误的结果

时间:2015-08-04 23:07:10

标签: sql-server

当我尝试将CTE与GROUP BY一起使用时,我偶然发现了一个问题。

我需要以“分组依据”的方式连接字符串,即从表中

   id value
   --------
    1    a
    1    b
    2    c
    2    d

我想得到以下结果:

id vals
1  a,b
2  c,d

以下查询将给出所需的结果([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;

但是,如果我用一个简单的CTE替换表#B:

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在没有任何警告的情况下返回错误的结果:

id vals
----------
1  a,b,c,d
2  a,b,c,d

任何人都可以解释上面的CTE查询是如何出错的吗?有趣的是知道SQL Server如何解释上面的CTE。谢谢。

1 个答案:

答案 0 :(得分:3)

您使用了别名a,它引用了您的CTE只需更改它并享受乐趣。我的意思是id=a.id a指的是自己。

with A as (
select * from #B
)
select id, 
    stuff((select distinct ','+value from A where id=b.id for xml path ('')),1,1,'') as vals 
from A as b 
group by id