我有这个查询:
select a.name, count(distinct numClient)
from a
group by a.name;
我想添加另一列,该列将为每一行计算前面几行的总和:
JONES 3 0
SMITH 5 3
JOHN 10 8
.....
KEN 12 365
你能帮我吗 ?。我想我必须使用分区但不太了解它。
您根本不需要子查询:
select a.name, count(distinct numClient),
(sum(count(distinct numClient)) over (order by count(distinct numClient)) -
count(distinct numClient)
) as running_sum
from a
group by a.name;
假设有一列指定计算累积和的顺序,您可以使用
select name,cntClient,sum(cntClient) over(order by orderCol rows between unbounded preceding and 1 preceding) as cumCntClient
from (select a.name, count(distinct numClient) as cntClient
from a
group by a.name
) t