简体   繁体   中英

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. 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.

The resulting table would look something like this

在此处输入图片说明

Is there an SQL command that can achieve this? (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. 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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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