0

我有这个查询:

select a.name, count(distinct numClient)
from a
group by a.name;

我想添加另一列,该列将为每一行计算前面几行的总和:

JONES     3      0
SMITH     5      3
JOHN      10     8
.....
KEN       12     365

你能帮我吗 ?。我想我必须使用分区但不太了解它。

4

2 回答 2

2

您根本不需要子查询:

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;
于 2018-09-18T10:45:58.833 回答
0

假设有一列指定计算累积和的顺序,您可以使用

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
于 2018-09-18T09:55:55.023 回答