简体   繁体   中英

Limit On Accumulated Column in MySQL

I'm trying to find an elegant way to write a query that only returns enough rows for a certain column to add up to at least n.

For example, let's say n is 50, and the table rows look like this:

id   count
1    12
2    13
3    5
4    18
5    14
6    21
7    13

Then the query should return:

id   count
1    12
2    13
3    5
4    18
5    14

Because the counts column adds up to n > 50. (62, to be exact)

It must return the results consecutively starting with the smallest id.

I've looked a bit into accumulators, like in this one: MySQL select "accumulated" column

But AFAIK, there is no way to have the LIMIT clause in an SQL query limit on an SUM instead of a row count.

I wish I could say something like this, but alas, this is not valid SQL:

SELECT *
FROM elements
LIMIT sum(count) > 50

Also, please keep in my the goal here is to insert the result of this query into another table atomically in an automated, performance efficient fashion, so please no suggestions to use a spreadsheet or anything that's not SQL compatible.

Thanks

There are many ways to do this. One is by using Correlated Subquery

SELECT id,
       count
FROM   (SELECT *,
               (SELECT Isnull(Sum(count), 0)
                FROM   yourtable b
                WHERE  b.id < a.id) AS Run_tot
        FROM   yourtable  a) ou
WHERE  Run_tot < 50 

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM