22,301
社区成员




if object_id('[tb]') is not null drop table [tb]
go
create table [tb]([ID] int,[NUM] int)
insert [tb]
select 1,1 union all
select 2,3 union all
select 3,2 union all
select 4,1 union all
select 5,4 union all
select 6,5 union all
select 7,3 union all
select 8,2 union all
select 9,1 union all
select 10,1
go
--select * from [tb]
with szx as
(
select *,path=cast(id as varchar(8000)),total=num from tb
union all
select b.id,b.num,a.path+'-'+rtrim(b.id),a.total+b.num
from szx a join tb b on a.id<b.id and a.total<15
)
select id,num from tb,(select top 1 path from szx where total=15 order by newid()) a
where charindex('-'+rtrim(id)+'-','-'+path+'-')>0