滚动计数SQL

时间:2017-05-09 16:02:25

标签: sql oracle

我有一个数据库,我在其中查询它以检索计数。我现在的问题是:我正在做一个如下所示的选择语句

Select count(distinct(ID)) as countID
      ,Activity
from Activity_Data
group by Activity_rank
order by countID desc

这让我回来了

Activity   Distinct Count
AAA        100
BBB        90
CCC        80

我想要实现的是滚动计数

Activity   Distinct Count   Rolling Count
AAA        100              100
BBB        90               190
CCC        80               270

我试过这个

    Select count(distinct(ID)) as countID
         , sum(count(distinct(ID))) as SumID
         , Activity from Activity_Data
    group by Activity_rank
    order by countID desc

但是它给了我一个而不是GROUP BY表达式

不太确定我做错了什么,并希望得到指导。

问候

2 个答案:

答案 0 :(得分:1)

你很亲密。您需要一个分析函数:

Select count(distinct ID) as countID,
       sum(count(distinct ID)) over (order by count(distinct ID) desc)
from Activity_Data
group by Activity_rank 
order by countID desc;

答案 1 :(得分:0)

我不相信你可以嵌套聚合函数。试着这样做:

WITH CTE AS (SELECT
Activity,
COUNT(DISTINCT ID) as CountID
FROM Activity_Data
GROUP BY Activity)

Select Activity, CountID, sum(CountID) OVER (ORDER BY ACTIVITY) as RollingSubtotal
FROM CTE
ORDER BY ACTIVITY