这是桌子T:-
T
id num ------- 1 50 2 20 3 90 4 40 5 10 6 60 7 30 8 100 9 70 10 80
而下面是一个 虚构的 sql
select * from T where sum(num) = '150'
预期的结果是:-
(一种)
id num ------- 1 50 8 100
(B)
id num ------- 2 20 7 30 8 100
(C)
id num ------- 4 40 5 10 8 100
最喜欢’A’的情况!
我知道这种情况与组合有关。
在现实世界中-客户从商店获得商品,并且由于他与商店之间达成协议,他每个星期五都付款。例如,付款金额不是项目的确切总和:他得到5册50钪(= 250钪)的书,而星期五他带来了150册。所以前3本书非常匹配-3 * 50 = 150.我需要找到那三本书的编号!
任何帮助,将不胜感激!
您可以在MSSQL中使用递归查询来解决此问题。
[SQLFiddle demo](http://sqlfiddle.com/#!6/1b720/39)
第一个递归查询建立一个树的累积总和<=150。第二个递归查询获取叶子的累积总和= 150,并将所有这样的路径输出到其根。另外,在按排序的最终结果中,ItemsCount您将首先获得首选的组(最少的项目数)。
ItemsCount
WITH CTE as ( SELECT id,num, id as Grp, 0 as parent, num as CSum, 1 as cnt, CAST(id as Varchar(MAX)) as path from T where num<=150 UNION all SELECT t.id,t.num, CTE.Grp as Grp, CTE.id as parent, T.num+CTE.CSum as CSum, CTE.cnt+1 as cnt, CTE.path+','+CAST(t.id as Varchar(MAX)) as path from T JOIN CTE on T.num+CTE.CSum<=150 and CTE.id<T.id ), BACK_CTE as (select CTE.id,CTE.num,CTE.grp, CTE.path ,CTE.cnt as cnt, CTE.parent,CSum from CTE where CTE.CSum=150 union all select CTE.id,CTE.num,CTE.grp, BACK_CTE.path,BACK_CTE.cnt, CTE.parent,CTE.CSum from CTE JOIN BACK_CTE on CTE.id=BACK_CTE.parent and CTE.Grp=BACK_CTE.Grp and BACK_CTE.CSum-BACK_CTE.num=CTE.CSum ) select id,NUM,path, cnt as ItemsCount from BACK_CTE order by cnt,path,Id