这是一个开始。它的性能会很差:
declare @Qs table (QuestionID int not null, QuestionMarks int not null)
insert into @Qs (QuestionID,QuestionMarks) values
(1,1), (2,4), (5,1), (9,1), (12,2)
declare @TargetMarks int = 8
declare @TargetCount int = 4
;with Build as (
select QuestionID as MinID,QuestionID as MaxID,QuestionMarks as Total,1 as Cnt
,'/' + CONVERT(varchar(max),QuestionID) + '/' as QPath
from @Qs
union all
select MinID,q.QuestionID,Total+q.QuestionMarks,Cnt+1,QPath + CONVERT(varchar(max),q.QuestionID) + '/'
from
Build b
inner join
@Qs q
on
b.MaxID < q.QuestionID and
b.Total + q.QuestionMarks <= @TargetMarks and
b.Cnt < @TargetCount
)
select * from Build where Cnt = @TargetCount and Total = @TargetMarks
结果集:
MinID MaxID Total Cnt QPath
--------------------------------------------------------------------------------
2 12 8 4 /2/5/9/12/
1 12 8 4 /1/2/9/12/
1 12 8 4 /1/2/5/12/
棘手的部分是 QPath 值并不是存储 ID 值的最佳方式。