首页 > 解决方案 > 如何创建查询以按表列mysql的总和进行过滤

问题描述

我有一些数据要根据数据的总和进行过滤,一个要清楚的例子:我有那个表

Nombre | nit | cantidad 
andres | 222 | 1.5
joseff | 555 | 2
juanca | 777 | 3.5
ivanll | 999 | 4
amxsof | 111 | 6.1

查询必须做的是,从该表中询问候选列的 SUM等于或小于(但尽可能接近)13 的行,我将返回以下内容:

Nombre | Nit | Cantidad 
joseff | 555 | 2
ivanll | 999 | 4
amxsof | 111 | 6.1

因为 2 + 4 + 6.1 = 12.1 的总和,这是可以用记录完成的最接近 13 的总和

标签: phpmysqlsqldatabase

解决方案


对于此类优化问题,SQL 并不是最优的。你可以做到,但这是蛮力。

如果您限制正在考虑的行数,它也会有所帮助。例如,如果您正在考虑最多 4 个组合:

select t1.nombre, t2.nombre, t3.nombre, t4.nombre,
       (coalesce(t1.cantidad, 0) + coalesce(t2.cantidad, 0) + coalesce(t3.cantidad, 0) + coalesce(t4.cantidad, 0)
       ) as total
from t t1 left join
     t t2
     on t1.nombre < t2.nombre left join
     t t3
     on t2.nombre < t3.nombre left join
     t t4
     on t3.nombre < t4.nombre
where (coalesce(t1.cantidad, 0) + coalesce(t2.cantidad, 0) + coalesce(t3.cantidad, 0) + coalesce(t4.cantidad, 0)
       ) <= 13
order by total desc
limit 1;

是一个 db<>fiddle。

如果要考虑其他组合,可以添加其他联接。


推荐阅读