SQL - 通过总计对结果进行分组

时间:2012-09-17 02:11:35

标签: sql oracle

以下查询为我提供了两列的输出:

Day Num_Users_Retained
0   209312
1   22139
2   11457

等等,一直到259(2012年的每一天)..但是我希望第0天在num_users_retained中包含所有值的总和,从0到259 ......然后我想要第1天包括1-259中所有值的总和,依此类推,直到我到达最后一天。这是原始查询:

--Retention since January 1,2012--
select retention as Day,count(retention) as Num_Users_Retained
from (select player_id,round(init_dtime-create_dtime,0) as retention
from player
where Trunc(Create_Dtime) >= To_Date('2012-jan-01','yyyy-mon-dd')
and init_dtime is not null)
Group by retention
order by 1 

有什么建议吗?

2 个答案:

答案 0 :(得分:2)

使用分析功能

select
    day,
    num_users_retained,
    sum(num_users_retained) over (order by day) as total_num_users_retained
from churn

http://www.sqlfiddle.com/#!4/24e02/1

此查询将写入结果集。您可以将其应用于原始查询。

答案 1 :(得分:1)

select retention as Day
     , Sum(count(retention)) over(order by retention desc) as Num_Users_Retained
 from (select player_id
            , round(init_dtime-create_dtime,0) as retention
        from player
       where Trunc(Create_Dtime) >= To_Date('2012-jan-01','yyyy-mon-dd')
         and init_dtime is not null
       )
Group by retention
order by retention