Oracle SQL - 运行 基于分组依据和条件求和
Oracle SQL - Running Sum based on group by and condition
我有 table 看起来像
ID SEQ LABEL COUNT
1 1 0 3
1 2 0 2
1 3 0 6
1 4 1 2
1 5 0 3
1 6 0 5
2 1 0 2
2 2 1 1
2 3 0 3
我想创建一个名为 running_count 的列。计算列数的累加和,直到Label为1,然后重新开始累加。
预期输出:
ID SEQ LABEL1 COUNT1 RUNNING_COUNT
1 1 0 3 3
1 2 0 2 5
1 3 0 6 14
1 4 1 2 16
1 5 0 3 3
1 6 0 5 8
2 1 0 2 2
2 2 1 1 3
2 3 0 3 3
我尝试了以下查询
SELECT A.*, SUM(COUNT1) over (partition by ID,LABEL1 order by SEQ) as RUNNING_COUNT FROM TABLE_1 A
这里的问题是对于 Label = 1,累积和停止在前一行(Seq)。我需要根据 Seq 为每个 ID 获取 运行 总和,直到 Label = 1。
我得到错误的输出
ID SEQ LABEL1 COUNT1 RUNNING_COUNT
1 1 0 3 3
1 2 0 2 5
1 3 0 6 14
1 4 1 2 2
1 5 0 3 3
1 6 0 5 8
2 1 0 2 2
2 2 1 1 1
2 3 0 3 3
您可以先创建一个 window sum()
来定义组,然后将其用作外部查询的分区:
select
t.*,
sum(count1) over(partition by id, grp order by seq) running_count
from (
select
t.*,
sum(label) over(partition by id order by seq desc) grp
from mytable t
) t
ID | SEQ | LABEL | COUNT1 | GRP | RUNNING_COUNT
-: | --: | ----: | -----: | --: | ------------:
1 | 1 | 0 | 3 | 1 | 3
1 | 2 | 0 | 2 | 1 | 5
1 | 3 | 0 | 6 | 1 | 11
1 | 4 | 1 | 2 | 1 | 13
1 | 5 | 0 | 3 | 0 | 3
1 | 6 | 0 | 5 | 0 | 8
2 | 1 | 0 | 2 | 1 | 2
2 | 2 | 1 | 1 | 1 | 3
2 | 3 | 0 | 3 | 0 | 3
我有 table 看起来像
ID SEQ LABEL COUNT
1 1 0 3
1 2 0 2
1 3 0 6
1 4 1 2
1 5 0 3
1 6 0 5
2 1 0 2
2 2 1 1
2 3 0 3
我想创建一个名为 running_count 的列。计算列数的累加和,直到Label为1,然后重新开始累加。
预期输出:
ID SEQ LABEL1 COUNT1 RUNNING_COUNT
1 1 0 3 3
1 2 0 2 5
1 3 0 6 14
1 4 1 2 16
1 5 0 3 3
1 6 0 5 8
2 1 0 2 2
2 2 1 1 3
2 3 0 3 3
我尝试了以下查询
SELECT A.*, SUM(COUNT1) over (partition by ID,LABEL1 order by SEQ) as RUNNING_COUNT FROM TABLE_1 A
这里的问题是对于 Label = 1,累积和停止在前一行(Seq)。我需要根据 Seq 为每个 ID 获取 运行 总和,直到 Label = 1。
我得到错误的输出
ID SEQ LABEL1 COUNT1 RUNNING_COUNT
1 1 0 3 3
1 2 0 2 5
1 3 0 6 14
1 4 1 2 2
1 5 0 3 3
1 6 0 5 8
2 1 0 2 2
2 2 1 1 1
2 3 0 3 3
您可以先创建一个 window sum()
来定义组,然后将其用作外部查询的分区:
select
t.*,
sum(count1) over(partition by id, grp order by seq) running_count
from (
select
t.*,
sum(label) over(partition by id order by seq desc) grp
from mytable t
) t
ID | SEQ | LABEL | COUNT1 | GRP | RUNNING_COUNT -: | --: | ----: | -----: | --: | ------------: 1 | 1 | 0 | 3 | 1 | 3 1 | 2 | 0 | 2 | 1 | 5 1 | 3 | 0 | 6 | 1 | 11 1 | 4 | 1 | 2 | 1 | 13 1 | 5 | 0 | 3 | 0 | 3 1 | 6 | 0 | 5 | 0 | 8 2 | 1 | 0 | 2 | 1 | 2 2 | 2 | 1 | 1 | 1 | 3 2 | 3 | 0 | 3 | 0 | 3