微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

sql server:选择总和匹配值的行

参见英文答案 > 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’案例是最优选的!

我知道这个案子与组合有关.

在现实世界中 – 客户从商店获取商品,并且由于他和商店之间的协议,他每周五付款.付款金额不是商品的确切总数
例如:他得到5本50欧元(= 250欧元)的书,周五他带150欧元,所以前3本书是完美匹配 – 3 * 50 = 150.我需要找到这3本书的id!

任何帮助,将不胜感激!

解决方法

您可以在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

原文地址:https://www.jb51.cc/mssql/83426.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐