行的滚动计数随着时间的推移?

时间:2017-02-22 00:07:49

标签: amazon-redshift

我在postgresql世界中发现了很多例子,但他们似乎都使用了redshift不支持的功能。

是否有一个简单的查询来获取每周的数字行数和滚动总和?

该表有一个"创建"这个列是没有时区的时间戳。

我最接近的是:

SELECT DISTINCT
       date_trunc('week', created) AS week
      ,count(*) OVER (ORDER BY date_trunc('week', created) rows unbounded preceding) AS running_ct
FROM   device_unlock_report
order by 1

这给了我:

2015-02-09 00:00:00 320
2015-02-09 00:00:00 321
2015-02-09 00:00:00 322
2015-02-09 00:00:00 323
2015-02-16 00:00:00 324
2015-02-16 00:00:00 325
2015-02-16 00:00:00 326
2015-02-16 00:00:00 327
2015-02-16 00:00:00 328

每次总和递增时似乎都给我一行。

1 个答案:

答案 0 :(得分:1)

对于Rolling Sum,请尝试

select week,total, sum(total) over (order by week rows unbounded preceding) as rolling_sum from
        (SELECT
        date_trunc('week', created) AS week,
        count(*) total
        FROM   device_unlock_report
        group by 1)
group by 1,2