根据组内列中的特定值求和值
Sum Values Based on Specific Value in a Column Within Group
我有一个顺序数据集,我需要按已解析的不同组对值求和。每次Distinct Group
列出现1,我想重新开始求和
提前致谢!! :)
原文Table:
Customer | Order_col | Name | Val | Distinct_Group
1 | 1 | A | 1 | 1
1 | 2 | A | 2 | 0
1 | 3 | A | 3 | 0
1 | 4 | B | 4 | 1
1 | 5 | C | 5 | 1
1 | 6 | C | 6 | 0
2 | 1 | A | 1 | 1
2 | 2 | B | 2 | 1
2 | 3 | D | 3 | 1
2 | 4 | D | 4 | 0
结果:
Customer | Name | Sum
1 | A | 6
1 | B | 4
1 | C | 11
2 | A | 1
2 | B | 2
2 | D | 7
想法是使用窗口化 SUM 生成 subgrp 列,然后将聚合 SUM 用于每个名称和 subgrp。
Name | Val | Distinct_Group | subgrp
A | 1 | 1 | 1
A | 2 | 0 | 1
A | 3 | 0 | 1
B | 4 | 1 | 2
C | 5 | 1 | 3
C | 6 | 0 | 3
查询:
WITH cte AS (
SELECT *, SUM(Distinct_Group) OVER(Partition by Customer ORDER BY Order Col) AS subgrp
FROM tab
)
SELECT Customer, Name, subgrp, SUM(Val) AS Sum
FROM cte
GROUP BY Customer, Name, subgrp;
我有一个顺序数据集,我需要按已解析的不同组对值求和。每次Distinct Group
列出现1,我想重新开始求和
提前致谢!! :)
原文Table:
Customer | Order_col | Name | Val | Distinct_Group
1 | 1 | A | 1 | 1
1 | 2 | A | 2 | 0
1 | 3 | A | 3 | 0
1 | 4 | B | 4 | 1
1 | 5 | C | 5 | 1
1 | 6 | C | 6 | 0
2 | 1 | A | 1 | 1
2 | 2 | B | 2 | 1
2 | 3 | D | 3 | 1
2 | 4 | D | 4 | 0
结果:
Customer | Name | Sum
1 | A | 6
1 | B | 4
1 | C | 11
2 | A | 1
2 | B | 2
2 | D | 7
想法是使用窗口化 SUM 生成 subgrp 列,然后将聚合 SUM 用于每个名称和 subgrp。
Name | Val | Distinct_Group | subgrp
A | 1 | 1 | 1
A | 2 | 0 | 1
A | 3 | 0 | 1
B | 4 | 1 | 2
C | 5 | 1 | 3
C | 6 | 0 | 3
查询:
WITH cte AS (
SELECT *, SUM(Distinct_Group) OVER(Partition by Customer ORDER BY Order Col) AS subgrp
FROM tab
)
SELECT Customer, Name, subgrp, SUM(Val) AS Sum
FROM cte
GROUP BY Customer, Name, subgrp;