限制为累计列数

时间:2018-10-08 08:52:30

标签: mysql sql limit

说我有一个包含3列的表格: id,row_type,row_score

我想选择第一行(或最后一行),但要根据获取的ID的累积得分来限制选择

示例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

2 个答案:

答案 0 :(得分:3)

此查询应执行您想要的操作。它使用变量来保持累积分数,然后在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

答案 1 :(得分:2)

这应该给您想要的结果:

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

谢谢

Rohan Hodarkar