簡體   English   中英

如何在SQL中滿足條件之前對行求和

[英]How to sum rows before a condition is met in SQL

我有一個表,其中有多個記錄具有相同的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中執行此操作。 先感謝您!

您可以使用一個簡單的匯總查詢與使用子查詢來恢復的條件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

DB Fiddle上的演示以及您的測試數據返回:

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

我想你要:

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;

基本的按查詢分組應該可以解決您的問題

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM