简体   繁体   English

SQL聚合和累积求和

[英]SQL Aggregation and cumulative summation

I have a user table which looks something like this 我有一个用户表,看起来像这样

在此处输入图片说明

There are many users with unique id's, the table is first ordered by users and then by datetime. 有许多具有唯一ID的用户,该表首先按用户排序,然后按日期时间排序。 Each instance is either a training or a test session, test sessions have additional arguments, most importantly score. 每个实例都是培训或测试会话,测试会话具有其他参数,最重要的是得分。

I would like to aggregate the rows of this table, so that the time of all the training sessions before a test session are summed and only one instance is returned with the cumulative training time and the test score. 我想汇总此表的行,以便将测试会话之前所有训练课程的时间相加,并且仅返回一个实例以及累积的训练时间和测试分数。 Every additional test before a new training session is just a repeat instance with the new test score. 在新的培训课程之前进行的每项其他测试只是具有新测试分数的重复实例。 This cumulative time summation continues until a new user (user id), when it is reset. 累计时间总和一直持续到重置新用户(用户ID)为止。

The resulting table would look something like this 结果表看起来像这样

在此处输入图片说明

Is there an SQL command that can achieve this? 是否有可以实现此目的的SQL命令? (self-join)? (自连接)?
The query doesn't have to be overly optimized, simple solutions are welcome. 查询不必过分优化,欢迎使用简单的解决方案。

Assign a group using a cumulative sum of the test s. 使用test s的累积和分配一个组。 Then aggregate to get the summaries you want within each group: 然后合计以获取每个组中所需的摘要:

select grp, user_id, sum(time), max(case when task = 'test' then time end) as test_time, max(score)
from (select t.*,
             sum(case when task = 'test' then 1 else 0 end) over (partition by user_id order by datetime) as grp
      from t
     ) t
group by grp, user_id;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM