现在这是一个有趣的 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 中执行此操作吗?
最佳答案
通过使用 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
关于mysql - 返回 nth 的倍数之和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10183460/