我期待在SQL中按日期生成一個簡單的累積總計,但會遇到看似簡單的問題。我制定了一項解決方案,但想象一下,如果沒有額外的步驟,就有辦法做我想做的事情。基本上我正在尋找的是:使用窗口函數在Postgres中按日期的累計總數
| Date | Count | | 2015-01-01 | 1 | | 2015-01-02 | 5 | | 2015-01-03 | 8 | | 2015-01-04 | 9 | | 2015-01-05 | 9 |
我們可以假設,表只有兩行 - id
和date
- 什麼我想看看到底是什麼是上面;然而,當我運行下面的代碼,我得到重複行:
SELECT date, count(*) over (order by date) AS cumulative_count FROM my_table;
返回:
| Date | Count | | 2015-01-01 | 1 | | 2015-01-02 | 5 | | 2015-01-02 | 5 | | 2015-01-02 | 5 | | 2015-01-02 | 5 | | 2015-01-02 | 5 | | 2015-01-03 | 8 | | 2015-01-03 | 8 | ...etc.
我的解決方法解決方案是使用SELECT DISTINCT date, count(*) over (order by date) AS cumulative_count FROM my_table;
但我想像有一個更好的我只是想念的方式。
在此先感謝!
我不認爲有什麼不妥是'DISTINCT'這裏。另請參閱:http://stackoverflow.com/questions/5698452/count-cumulative-total-in-postgresql – 2015-03-02 18:54:21
爲什麼在這種情況下使用窗口函數? – 2015-03-02 19:04:32
有沒有更簡單的方法來獲得累計/運行總數而不使用窗口函數? – AvocadoRivalry 2015-03-02 19:20:55