sql server:选择总和匹配值的行
发布时间:2020-12-12 16:25:37 所属栏目:MsSql教程 来源:网络整理
导读:参见英文答案 How to get rows having sum equal to given value4个 这是表T: – id num------- 1 50 2 20 3 90 4 40 5 10 6 60 7 30 8 100 9 7010 80 以下是一个虚构的SQL select *from Twhere sum(num) = '150' 预期的结果是: – (一个) id num------- 1
参见英文答案 >
How to get rows having sum equal to given value4个
这是表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’案例是最优选的! 我知道这个案子与组合有关. 在现实世界中 – 客户从商店获取商品,并且由于他和商店之间的协议,他每周五付款.付款金额不是商品的确切总数 任何帮助,将不胜感激! 解决方法您可以在MSSQL中使用递归查询来解决此问题.SQLFiddle demo 第一个递归查询构建具有累积和< = 150的项目树.第二个递归查询采用具有累积和= 150的叶子并将所有这些路径输出到其根.同样在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,BACK_CTE.path,BACK_CTE.cnt,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,Id (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |