Home » Php » php – How create a query to filter by the total sum of an table column mysql

php – How create a query to filter by the total sum of an table column mysql

Posted by: admin February 25, 2020 Leave a comment

Questions:

I have a quantity of data that I want to filter depending on the sum of the data, an example to be clear: I have that table

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

The query would have to do is, ask from this table the rows whose SUM of the cantidad column is equal or less (but as close as possible) than 13, and I would return the following:

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

because the sum of 2 + 4 + 6.1 = 12.1, which is the closest sum to 13 that can be done with the records

How to&Answers:

SQL is not optimal for this type of optimization problem. You can do it, but it is brute force.

It also helps if you are limiting the number of rows that you are considering. For instance, if you are considering combinations up to 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;

Here is a db<>fiddle.

If you want to consider additional combinations, you can add additional joins.