【问题标题】:在mysql中达到目标的累积总和
【发布时间】:2022-01-07 16:49:57
【问题描述】:

我有以下表格,

锻炼数据:

Date       User        Distance     Calories        
1614944833   1           100            32
1614944232   2           100            43
1624944831   1           150            23
1615944832   3           250            63
1614644836   1           500            234 
1614954835   2           100            55
1614344834   3           100            34
1614964831   1           260            23
1614944238   1           200            44

user_subdomain 数据:

    User        sub_domain
    1           3
    2           3           
    3           3
    4           2

子域数据:

    subdomain       name
    3               test1 
    4               test2

一旦用户达到距离总和 >= 1000,我想获得距离、卡路里、记录数的总和。如果用户超过 1000 距离,我们不应该计算剩余记录。(如果用户超过 1000,则 1000 否则最大距离值)。

预期输出:

Date       record_count Distance    Calories    
1614964831   4          1000        312
1614954835   2          200         98
1614344834   3          350         97

所以这个结果显示每个用户通过record_count达到距离1000的总努力,然后如果他们达到1000以上然后计算为1000,否则最大达到距离值,然后该卡路里的总和直到达到1000的累积总和。这个是我需要检索的输出。我尝试使用以下查询,但不起作用

任何人都可以建议使用累积和内连接方法或任何其他解决方案吗?

【问题讨论】:

  • 我想你想看看 GROUP BY 以及 SUM
  • 是的,但如果用户达到 1000,则无法跳过剩余记录。这是问题
  • 距离超过 1000 可以由显示逻辑处理,或者可能是 MAX。 1000 距离后要忽略卡路里吗?
  • 是的,上面的锻炼表有5条用户ID 1的记录。用户通过前4条记录超过1000,因此需要将前4条记录的卡路里和距离相加为1000,然后record_count为4.like that我需要检索,在此计算中将跳过最后 5 条记录
  • 请说明读取记录的顺序,预期结果不按任何列排序。

标签: mysql aggregate-functions cumulative-sum


【解决方案1】:

从 MySQL 8.0 开始,您可以在下一个方式中使用window functions

with cumulative as (
  -- calculate cumulative Distance & Calories
  select 
      User,
      Distance,
      Calories,
      sum(Distance) over (partition by User order by Date) SumDistance,
      sum(Calories) over (partition by User order by Date) SumCalories
  from Workout
  order by User, Date
) select 
    User, max(SumDistance), max(SumCalories)
from cumulative
where SumDistance - Distance < 1000 -- filter
group by User;

MySQL window functions

【讨论】:

  • 真的很近,但我认为他们也想在达到距离时扔掉卡路里。 dbfiddle.uk/…
  • 此查询在 phpmyadmin 中不起作用并显示语法错误
  • 你有什么 MySQL 版本?
猜你喜欢
  • 2016-12-10
  • 2021-05-13
  • 2020-03-30
  • 1970-01-01
  • 2021-03-26
  • 1970-01-01
  • 2021-06-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多