PostgreSQL- sum不被识别为聚合函数?

时间:2017-03-28 12:37:10

标签: postgresql aggregate-functions running-total

我需要每年运行的交易量。因此,如果2015的总金额为1502016,则总金额为90。这意味着2016运行金额为240。等等。

所以我有这些数据:

CREATE table transactions2(year_num int, amount int);

insert into transactions2 values(2015, 100);
insert into transactions2 values(2015, 50);
insert into transactions2 values(2016, 90);
insert into transactions2 values(2017, 100);
insert into transactions2 values(2019, 200);

SELECT year_num, count(amount), sum(amount) 
OVER (ORDER BY year_num) 
FROM transactions2 
GROUP BY year_num ORDER BY year_num;

如果我运行这个选择SQL,我得到:

ERROR:  column "transactions2.amount" must appear in the GROUP BY clause or be used in an aggregate function
LINE 9: SELECT year_num, count(amount), sum(amount) OVER (ORDER BY y...
                                            ^

********** Error **********

ERROR: column "transactions2.amount" must appear in the GROUP BY clause or be used in an aggregate function
SQL state: 42803
Character: 328

但我在amount函数中有sum。那么为什么它不起作用?如果我像sum(count(sum))一样包裹它,那么它可以工作,但我不需要计算总数,我只需要求和。

我是否需要为此编写内部选择?

1 个答案:

答案 0 :(得分:3)

在表达式中:

sum(amount) OVER (ORDER BY year_num) 

sum()不是一个简单的聚合,它是一个窗函数。

您可能希望同时使用count()sum()作为窗口函数:

SELECT DISTINCT year_num, count(amount) over w, sum(amount) over w
FROM transactions2 
WINDOW w as (ORDER BY year_num)
ORDER BY year_num;

 year_num | count | sum 
----------+-------+-----
     2015 |     2 | 150
     2016 |     3 | 240
     2017 |     4 | 340
     2019 |     5 | 540
(4 rows)