【问题标题】:PostgreSQL- sum not recognized as aggregate function?PostgreSQL- sum 不被识别为聚合函数?
【发布时间】:2017-08-21 12:58:47
【问题描述】:

我需要每年有连续的交易量。因此,如果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

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

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

【问题讨论】:

  • 为什么 OVER (ORDER BY year_num) ?
  • @Jack 因为我需要按照问题中的说明运行总金额。它必须将上一年的总数添加到明年,依此类推。有了OVER,就可以搞定。
  • 好吧——我从来没有用过 OVER 来做这样的事情;我会用内部查询编写它
  • sum(sum(amount)) over ... 也应该可以工作,但@klin 的回答更简单(并且已经解释了原因)。

标签: postgresql aggregate-functions cumulative-sum


【解决方案1】:

在表达式中:

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)

【讨论】:

  • 因为我忘记了 DISTINCT,抱歉。答案已编辑。
猜你喜欢
  • 2020-08-05
  • 1970-01-01
  • 1970-01-01
  • 2014-02-24
  • 2019-10-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多