选择值总和等于特定值的所有记录

Thi*_*ias 3 mysql

我有一个products看起来像这样的表(为了简单起见,隐藏了其他字段)

id | price
----------
1  |  199
2  |  50
3  |  320
4  |  120
Run Code Online (Sandbox Code Playgroud)

我正在尝试创建一个查询来选择值等于或小于特定值的所有产品,例如:

客户希望最多花费 600 美元,应退回示例中的前 3 件产品 ( 199+50+320 = 569 )

我尝试使用下面的查询但没有成功

select * from products group by id having sum(price) <= 600
Run Code Online (Sandbox Code Playgroud)

Erg*_*sha 5

我正在尝试创建一个查询来选择值等于或小于特定值的所有产品

我们需要为这种情况创建一个累积和。

select id,
       price
from ( SELECT id,
              price,
              SUM(price) OVER(ORDER BY id asc ) AS cumulative_sum
       FROM products
     ) cum_sum
where cumulative_sum <=600;
Run Code Online (Sandbox Code Playgroud)

https://dbfiddle.uk/8A46Gmcy

注意,以上累计和是按 id 排序的,这意味着它将测试第一个产品。

如果 id 1 等于 601 查询将返回空集。

您可以根据需要更改累积 SUM 的顺序。

 SUM(price) OVER(ORDER BY price asc ) AS cumulative_sum  ---will start from the lowest price to max
Run Code Online (Sandbox Code Playgroud)

编辑更合适的答案/问题是找到总和小于 600 的所有可能的值组合。

with recursive cte as ( 
    select id as max_id,
           price,
           cast(id as char(255))  as possible_combination 
           from products
  union all
    select p.id as max_id,
           c.price + p.price as price,
           cast(concat(c.possible_combination ,',' , p.id) as char(255))  as possible_combination
   from cte c
   inner join products p on p.id > c.max_id                       
)
select possible_combination,price
from cte
where price <= 600 ;
Run Code Online (Sandbox Code Playgroud)

https://dbfiddle.uk/IaqXBqzi