我可以使用 sum()
函数进行直接求和。但我这里的情况有所不同。我有一个只有 2 个字段的表 Student。例如,假设全类只有 1 名学生:
CREATE TABLE student
(`dateOfExam` date, score int)
;
INSERT INTO student
(`dateOfExam`, `score`)
VALUES
('2020-05-28',5),
('2020-05-29',5),
('2020-05-30',10),
('2020-06-03',10),
('2020-06-05',5),
('2020-07-21',20),
('2020-07-22',10),
('2020-07-28',10)
;
我有他参加考试的分数,运行时中还有一列,即举行考试的月份:
查询是(昨天从 stackoverflow 获得帮助):
select date_format(dateOfExam, '%Y-%m') ExamMonth
, dateOfExam
, score
from student;
结果:
+-----------+------------+-------+
| ExamMonth | dateOfExam | score |
+-----------+------------+-------+
| 2020-05 | 2020-05-28 | 5 |
| 2020-05 | 2020-05-29 | 5 |
| 2020-05 | 2020-05-30 | 10 |
| 2020-06 | 2020-06-03 | 10 |
| 2020-06 | 2020-06-05 | 5 |
| 2020-07 | 2020-07-21 | 20 |
| 2020-07 | 2020-07-22 | 10 |
| 2020-07 | 2020-07-28 | 10 |
+-----------+------------+-------+
我的要求是我想每个月奖励这个学生。我将继续在每个月的每个日期添加他的分数,并在累积分数总和达到 10 时给予他“奖励 1”,并在累积分数总和达到 20 时给予他奖励2。决赛 table 应该是这样的:
+---------------+---------------+-------+---------------+---------------+
| ExamMonth | dateOfExam | Score | Reward1 | Reward2 |
+---------------+---------------+-------+---------------+---------------+
| 2020-05 | 2020-05-28 | 5 | | |
| | 2020-05-29 | 5 | Y | |
| | 2020-05-30 | 10 | | Y |
|---------------|---------------|-------|---------------|---------------|
| 2020-06 | 2020-06-03 | 10 | Y | |
| | 2020-06-05 | 5 | | |
|---------------|---------------|-------|---------------|---------------|
| 2020-7 | 2020-07-21 | 20 | Y | Y |
| | 2020-07-22 | 10 | | |
| | 2020-07-28 | 10 | | |
+---------------+---------------+-------+---------------+---------------+
奖励字段可以是 bool 值,空奖励行可以设置为 N 或 False 或任何看起来合乎逻辑的值。 这没有帮助: Calculate running sum
请帮助我实现这个目标。建议一些方法。
这是一个fiddle .
最佳答案
首先计算 CTE 中每个月分数的运行总和。
然后应用您的条件:
with cte as (
select date_format(dateOfExam, '%Y-%m') ExamMonth,
dateOfExam, score,
sum(score) over (partition by date_format(dateOfExam, '%Y-%m') order by dateOfExam) total
from student
)
select ExamMonth, dateOfExam, score,
case when sum(total >= 10) over (partition by ExamMonth order by dateOfExam) = 1 then 'Y' end Reward1,
case when sum(total >= 20) over (partition by ExamMonth order by dateOfExam) = 1 then 'Y' end Reward2
from cte
请参阅demo .
结果:
> ExamMonth | dateOfExam | score | Reward1 | Reward2
> :-------- | :--------- | ----: | :------ | :------
> 2020-05 | 2020-05-28 | 5 | null | null
> 2020-05 | 2020-05-29 | 5 | Y | null
> 2020-05 | 2020-05-30 | 10 | null | Y
> 2020-06 | 2020-06-03 | 10 | Y | null
> 2020-06 | 2020-06-05 | 5 | null | null
> 2020-07 | 2020-07-21 | 20 | Y | Y
> 2020-07 | 2020-07-22 | 10 | null | null
> 2020-07 | 2020-07-28 | 10 | null | null
关于mysql - 如何计算MySQL中每个组的运行总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63986019/