I am trying to find cumulative sum of a column. Know that, window function can achieve this, however I want to achieve this using variables. This is my code.
DECLARE csum INTEGER := 0;
SELECT
employee_id,
department_id,
boss_id,
name,
salary,
(csum := csum salary) AS cum_salary
FROM employees
I get the below error message. How do i fix this ?
org.postgresql.util.PSQLException: ERROR: syntax error at or near "INTEGER"
Position: 14
DECLARE csum INTEGER := 0;
^
SELECT
EDIT : I was trying to achieve something similar I have done in MySQL. However, realised that PostgreSQL doesn't support this. Thanks.
CodePudding user response:
No need for a hack with variables (which don't exist in standard SQL or Postgres to begin with).
This can easily be done using a window function. However a cumulative sum only makes sense if you also provide a sort order for the rows.
SELECT
employee_id,
department_id,
boss_id,
name,
salary,
sum(salary) over (order by ????)
FROM employees