php - 如何创建查询以按表列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 的总和
解决方案
对于此类优化问题,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。
如果要考虑其他组合,可以添加其他联接。
推荐阅读
- c++ - map::erase 如何知道间隔是否有效?
- substrate - 升级后断链:致命:无法初始化 API:-32603:发生未知错误:
- jmeter - s3 中的 Jmeter 仪表板显示不正确
- c# - 清除缓存以从 Request.Form 中获取值
- wget - 如何使 wget 从不同的链接下载具有相同名称的文件,而不是从相同的链接?
- python-3.x - 仅当行满足 Pandas 的某些条件时,才计算每组的滚动函数
- reactjs - react-hook-form 提交后无法正确验证 value 和 onChange
- java - 如果全局请求映射,请一起使用 Spring Boot 资源映射
- git - Go exec 不捕获 git log 输出
- python - 如何在 Pandas DataFrame 的一行中传递 XML 中不同标签的元素?