如何在SQL中满足条件之前对行求和

时间:2019-02-13 23:24:54

标签: sql presto

我有一个表,其中有多个记录具有相同的ID。看起来像这样,并且行按序列号排序。

+----+--------+----------+----------+
| id | result | duration | sequence |
+----+--------+----------+----------+
| 1  | 12     | 7254     | 1        |
+----+--------+----------+----------+
| 1  | 12     | 2333     | 2        |
+----+--------+----------+----------+
| 1  | 11     | 1000     | 3        |
+----+--------+----------+----------+
| 1  | 6      | 5        | 4        |
+----+--------+----------+----------+
| 1  | 3      | 20       | 5        |
+----+--------+----------+----------+
| 2  | 1      | 230      | 1        |
+----+--------+----------+----------+
| 2  | 9      | 10       | 2        |
+----+--------+----------+----------+
| 2  | 6      | 0        | 3        |
+----+--------+----------+----------+
| 2  | 1      | 5        | 4        |
+----+--------+----------+----------+
| 2  | 12     | 3        | 5        |
+----+--------+----------+----------+

例如对于id=1,我想对之前所有行的持续时间求和,并包括result=6,即7254+2333+1000+5。与id =2相同,它将为230+10+0。在行result=6后面的所有内容。

我的预期输出:

+----+----------+
| id | duration |
+----+----------+
| 1  | 10592    |
+----+----------+
| 2  | 240      |
+----+----------+

序列必须按升序排列。

我不确定如何在sql中执行此操作。 预先谢谢你!

3 个答案:

答案 0 :(得分:1)

您可以使用简单的聚合查询,其条件是使用子查询来恢复与序列为sequence的记录相对应的6

SELECT t.id, SUM(t.duration) total_duration
FROM mytable t
WHERE t.sequence <= (
    SELECT sequence
    FROM mytable
    WHERE id = t.id AND result = 6
)
GROUP BY t.id

demo on DB Fiddle 与您的测试数据一起返回:

| id  | total_duration |
| --- | -------------- |
| 1   | 10592          |
| 2   | 240            |

答案 1 :(得分:1)

我想你想要

select t2.id, sum(t2.duration)
from t
where t.sequence <= (select t2.sequence
                     from t t2
                     where t2.id = t.id and t2.result = 6
                    );

在PrestoDB中,我建议使用窗口功能:

select id, sum(duration)
from (select t.*,
             min(case when result = 6 then sequence end) over (partition by id) as sequence_6
      from t
     ) t
where sequence <= sequence_6;

答案 2 :(得分:0)

基本按查询分组应该可以解决您的问题

select 
  id,
  sum(duration) duration
from t
group by id

对于某些行:

select 
  id,
  sum(duration) duration
from t
where id = 1
group by id

如果要将其包含在结果集中

select id, duration, sequence from t 
union all
select 
  id,
  sum(duration) duration
  null sequence
from t
group by id