PostgreSQL- sum 不被识别为聚合函数?
PostgreSQL- sum not recognized as aggregate function?
我需要每年进行 运行ning 笔交易。因此,如果 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;
如果我运行这个selectSQL,我得到:
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))
,那么它就可以工作,但我不需要计数总和,我只需要总和。
我是否需要为此编写内部 select?
表达式中:
sum(amount) OVER (ORDER BY year_num)
sum()
不是一个简单的聚合,它是一个 window 函数。
您可能想同时使用 count()
和 sum()
作为 window 函数:
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)
我需要每年进行 运行ning 笔交易。因此,如果 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;
如果我运行这个selectSQL,我得到:
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))
,那么它就可以工作,但我不需要计数总和,我只需要总和。
我是否需要为此编写内部 select?
表达式中:
sum(amount) OVER (ORDER BY year_num)
sum()
不是一个简单的聚合,它是一个 window 函数。
您可能想同时使用 count()
和 sum()
作为 window 函数:
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)