I need to have running amount of transactions per year. So if total amount at 2015 was 150 and at 2016, total amount was 90. It means at 2016 running amount is 240. And so on.
So I have this data:
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;
If I run this select SQL, I get:
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
But I have amount in sum function. So Why it is not working? If I wrap it like sum(count(sum)), then it works, but I do not need to have sum of count, I just need sum.
Do I need to write inner select just for this?
OVER, it can be done.sum(sum(amount)) over ...should work too, but @klin's answer is easier (and already explains why).