gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 12:42:28 25 4
gpt4 key购买 nike

我需要有每年运行的交易量。因此,如果 2015 的总金额为 150,而 2016 的总金额为 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)),那么它就可以工作,但我不需要计数总和,我只需要总和。

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

最佳答案

在表达式中:

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)

关于PostgreSQL- sum 不被识别为聚合函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43069788/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com