0
現在,類似的問題已經被問了幾次在這個論壇的共有,但是,我已經被計算在posrgresql (Version 9.4.2)
表中的列的每月運行總和掙扎:posrgresql:混淆運行列
created_at | points
-----------------------------
2015-12-10 12:26:34 | 199
2016-01-10 12:26:34 | 199
2016-02-10 12:26:34 | 199
2016-03-10 12:26:34 | 500
2016-03-10 12:26:39 | 199
預期的結果是:
created_at | sum
-----------------------------
2015-12-01 | 199
2016-01-01 | 398
2016-02-01 | 597
2016-03-01 | 1296
工作sql
我到達,主要是通過試驗和錯誤讀取其他線程後,是:
SELECT
date_trunc('month',created_at)::date as month_created,
sum(sum(points))
OVER
(
ORDER BY date_trunc('month',created_at)::date
)
FROM
point_histories
GROUP BY 1
ORDER BY 1 ASC
我的困惑是爲什麼以下(我顯然是誤解)工作?
SELECT
month_created,
sum(points),
sum(sum(points))
OVER
(
PARTITION BY month_created
ORDER BY created_at
)
AS cum_amt
FROM
(
SELECT
*,
date_trunc('month', created_at)::date as month_created
FROM
point_histories
)
as derivedTable
ORDER BY created_at
GROUP BY month_created
上面提供了以下錯誤:
********* Error **********
ERROR: syntax error at or near "group"
SQL state: 42601
Character: 314
如果我刪除GROUP BY
條款,我得到:
********** Error **********
ERROR: column "derivedtable.month_created" must appear in the GROUP BY clause or be used in an aggregate function
SQL state: 42803
Character: 12
這給了'錯誤:列「derivedtable.created_at」必須出現在GROUP BY子句或聚集function' –
使用@CodePoet我從來沒有與「過度」的工作,但我在Postgres 9.3和這裏測試一個普通的查詢...如果組和順序不正確,我得到了你的錯誤......我將編輯我的答案來說明 – OkieOth