2017-02-22 82 views
0

我在postgresql世界裏發現了很多例子,但它們似乎都使用了紅移不支持的函數。隨着時間的推移滾動計數的行數?

是否有一個簡單的查詢來獲取每週的數字行,滾動的總和?

該表具有「已創建」列,該列是沒有時區的時間戳。

我已經得到最接近的是:

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 

似乎每次都要給我一個行之和的增量。

+0

類似:[紅移 - 計算的月活躍用戶(http://stackoverflow.com/q/42261489/174777) –

+0

需要使用'GROUP BY 1'而不是'DISTINCT' –

回答

1

滾動總和,儘量

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