First, I have not even started coding this query yet simply because I don't know how to approach it. The scenario is this. In table_name I need to query against column_a selecting (all columns in) the rows that best sum up to a determined value. My value for this example could be 150. results in column_a could be (3,25,67,19,9,11) etc. I need the five rows that when added together will be closest to 150. In this case the query would give me rows (67,25,19,11,9).
SELECT * FROM 5 rows -> WHERE SUM(column_a) closest matches 150
this example is close to what I am looking for except I need the total and the rows resulting. Sum top 5 values in MySQL
I hope i have explained this well enough. I have a feeling this will be a simple problem I've just simply way over thought.
Thanks
with a table t with one column val
select * from t as t1, t as t2, t as t3, t as t4, t as t5
order by abs(t1.val + t2.val + t3.val + t4.val + t5.val - 150)
limit 1
Note that this will be a slow query.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.