代码之家  ›  专栏  ›  技术社区  ›  Guy Louzon

按累计列金额限制

  •  1
  • Guy Louzon  · 技术社区  · 7 年前

    假设我有一个有3列的表: id,行类型,行分数

    我想选择第一(或最新)行,但根据获取的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 回复  |  直到 7 年前
        1
  •  3
  •   Nick SamSmith1986    7 年前

    此查询应该满足您的要求。它使用一个变量来保存一个累积分数,然后在 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

        2
  •  2
  •   Rohan Hodarkar    7 年前

    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
    

    谢谢,