use SUM_ten
if object_id('[tb]') is not null drop table [tb]
go
create table [tb](id int,数据 int)
insert tb select '1',10000
union all select '2',1300
union all select '3',25000
union all select '4',809
union all select '5',555
union all select '6',2000
union all select '7',20000
union all select '8',102
union all select '9',111
union all select '10',940;
with cte as
(select top 100 percent id,cast(id as varchar(max)) as ch,数据 from tb order by 数据 DESC --基表,只在第一次运行
union all
--递归表,第二次运行,接着第一次结果
select b.id, a.ch+rtrim(b.id), a.数据+b.数据
from cte a,tb b where charindex(rtrim(b.id),a.ch)=0 and b.id>a.id)
select top 20 id,ch,数据 from cte where 数据>=30000
一个sql server的cte问题,如代码所示,希望求10个数据中,相加大于等于3万的20组数,我的理解是cte运行时,第一次运行基表,然后得到由大到小排列的10个数,以此当做第二次运行(递归)的开始,所以计算时,第一组数是3 7
ID ch 数据
7 37 45000
8 378 45102
以此类推。
但是,当我把第8、9个数换成‘10200’和‘11111’时,它的查询结果就变成了
ID ch 数据
8 78 30200
9 79 31111
这个样子,7 8 成了第一组数,这样就违反了我之前的认为。所以,cte到底是怎么运行的啊???到底哪里错了?