posrgresql:运行总列的混乱

时间:2016-03-10 19:18:00

标签: postgresql

现在,在这个论坛中已经多次提出过类似的问题,但是,我一直在努力计算posrgresql (Version 9.4.2)表中列的每月运行总和:

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

1 个答案:

答案 0 :(得分:0)

IMO,order by子句应该完成你的查询。

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
GROUP BY month_created
ORDER  BY created_at