mysql - 选择SUM达到700的记录

标签 mysql sql database

我有一个分数表,其中每条记录都带有可变的分数、时间戳和移动用户 ID。

this is what the table looks like

我的任务是计算出用户获得 700 分所需的平均时间。

如何使用 SQL 找出total_points 总和达到 700 的记录 id,以便比较时间戳并为每个用户执行此操作。

Python 脚本是解决这个问题的最佳方法吗?假设我获得了数据库中积分 >= 700 分的用户的 2 个时间戳(第一个时间戳,以及 Total_points 达到 700 的时间戳),以便得出所有用户的平均时间。

或者这是否可以在不编写脚本的情况下完成?

感谢任何帮助或指导。

最佳答案

给你。如果数据是:

create table score (
  id int,
  mobile_user_id int,
  report_date datetime,
  total_points int
);

insert into score (id, mobile_user_id, report_date, total_points)
  values
  (1, 123, '2018-07-23', 100),
  (1, 123, '2018-07-24', 200),
  (1, 123, '2018-07-25', 500),
  (1, 123, '2018-07-26', 200),
  (2, 124, '2018-06-03', 800),
  (3, 125, '2018-06-17', 150);

查询是:

with a as (
  select
      id, mobile_user_id, report_date,
      sum(total_points) over(partition by id order by report_date)
        as points_so_far
    from score
), 
b as (
  select id, min(report_date) as obtain_date
    from a where points_so_far >= 700
    group by id
)
select s.id, s.initial_date, b.obtain_date
  from b join (
    select id, min(report_date) as initial_date 
      from score group by id  
  ) s on s.id = b.id;

结果:

id           initial_date         obtain_date          
-----------  -------------------  ---------------------
1            2018-07-22 20:00:00  2018-07-24 20:00:00  
2            2018-06-02 20:00:00  2018-06-02 20:00:00  

关于mysql - 选择SUM达到700的记录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51955943/

相关文章:

PHP PDO 调用非对象上的成员函数 execute()

database - 管理 H2 数据库的前端工具

PHP foreach 循环返回额外值

mysql - 奖品表的数据库建模,允许根据比赛进行定制

java - 如何在多节点生产服务器上迁移数据库?

mysql - SQL分组相同的名字

MySQL - 行到列

database - 我关闭SSH连接时Neo4j通常会崩溃

mysql - 如何获取mysql中所有值都相同的行

mysql - 选择首先计数或数据以检查自动增量 ID