返回n次的倍数

时间:2012-04-17 00:22:17

标签: mysql

现在这是一个有趣的MySQL问题,我想知道它是否可能!

免责声明:虽然这是我之前提出过的非常类似的问题,但它实际上完全不同。只是在有人说我以前问过这个问题之前说。

就本例而言,我想要{20}的倍数为SUMS()

我想SUM()行分数并返回日期。

假设我有下表按date ASC排序:

数据

score |   date
  4     2000-01-01
  2     2000-01-02
  6     2000-01-03
  1     2000-01-04 //Score 4+2+6+1 = 13
  7     2000-01-05 //Score 4+2+6+1+7 = 20 so return this date
  1     2000-01-06
  2     2000-01-07
  1     2000-01-08
  5     2000-01-09
  1     2000-01-10
  9     2000-01-11 //Score = 39 so far.
  7     2000-01-12 //Score = 46 It's not 40 but is the closest number above 40 so return it.
  3     2000-01-13
  4     2000-01-14
  7     2000-01-15 //Score = 60, return this date.

预期结果:

score | date
 20     2000-01-05
 40     2000-01-12
 60     2000-01-15

等等。是否可以在MySQL中执行此操作?

2 个答案:

答案 0 :(得分:3)

当然,一切皆有可能:)

select
    floor(partial / 20) * 20, min(date)
from
    (select
        (select sum(score) from Scores s2
         where s2.date <= s.date) as partial,
        score,
        date
    from
        Scores s) p
where
    floor(partial / 20) > 0
group by
    floor(partial / 20)

演示:http://www.sqlfiddle.com/#!2/d44cf/3

答案 1 :(得分:3)

通过使用SQL变量,您不必继续为每个后续行执行递归聚合以计算到给定实体。这将按顺序执行每一个标记,其中一个触发20的倍数。然后仅在“ThisOne”标志设置为1的情况下处理该结果。

select 
      M20.*
   from 
      ( select 
              TransDate,
              score,
              if( @runTotal + Score >= 20 * @multCnt, 1, 0 ) as ThisOne,
              @multCnt := @multCnt + if( @runTotal + Score >= 20 * @multCnt, 1, 0 ) as nextSeq,
              @runTotal := @runTotal + Score
           from Mult20s,
                ( select @multCnt := 1,
                         @runTotal := 0 ) sqlvars
           order by transdate ) M20
   where
      M20.ThisOne = 1