受累积列数量限制

Limit by a cumulative column amount

假设我有一个包含 3 列的 table: id, row_type, row_score

我想 select 第一行(或最新的)行,但是 selection 基于获取的 ids 的累积分数限制

例子table

id | row_type | row_score
 1          a                  1
 2          a                  1
 3          b                  2
 4          c                  3
 5          a                  1
 6          b                  2
 7          a                  1
...

第一行的结果,累计分数限制为4:

id | row_type | row_score
 1          a                  1
 2          a                  1
 3          b                  2

此查询应该可以满足您的要求。它使用一个变量来保持累积分数,然后在 HAVING 子句中使用它来限制返回的行:

SELECT t1.*, @cum_score := @cum_score + row_score AS cum_score
FROM table1 t1
JOIN (SELECT @cum_score := 0) c
HAVING cum_score <= 4
ORDER BY cum_score

输出:

id  row_type    row_score   cum_score
1   a           1           1
2   a           1           2
3   b           2           4

SQLFiddle Demo

这应该会给你想要的结果:

select t1.id, t1.row_type,t1.row_score, SUM(t2.row_score) as sum
from table t1
inner join table t2 
on t1.id >= t2.id
group by t1.id, t1.row_type,t1.row_score
having SUM(t2.row_score)<=4
order by t1.id

谢谢,

罗汉霍达卡