简体   繁体   English

MySQL中累积列的限制

[英]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. 我正在尝试找到一种优雅的方式来编写查询,该查询仅返回足够的行以使特定列的总和至少为n。

For example, let's say n is 50, and the table rows look like this: 例如,假设n为50,并且表行如下所示:

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) 因为counts列总计n>50。(准确地说是62)

It must return the results consecutively starting with the smallest id. 它必须从最小的id开始连续返回结果。

I've looked a bit into accumulators, like in this one: MySQL select "accumulated" column 我对累加器进行了一些研究,例如: MySQL选择“累加”列

But AFAIK, there is no way to have the LIMIT clause in an SQL query limit on an SUM instead of a row count. 但是AFAIK不能在SUM的SQL查询限制中使用LIMIT子句来代替行数。

I wish I could say something like this, but alas, this is not valid SQL: 希望我可以这样说,但是,这不是有效的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. 另外,请记住我的目标是以自动,高效的方式将查询结果原子地插入到另一个表中,因此,不建议使用电子表格或任何与SQL不兼容的内容。

Thanks 谢谢

There are many ways to do this. 有很多方法可以做到这一点。 One is by using Correlated Subquery 一种是通过使用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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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