简体   繁体   English

PostgreSQL:使用变量时出现语法错误

[英]PostgreSQL : syntax error in while using variable

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.知道,window function 可以实现这个,但是我想用变量来实现这个。 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.编辑:我试图实现我在 MySQL 中所做的类似事情。 However, realised that PostgreSQL doesn't support this.然而,意识到 PostgreSQL 不支持这个。 Thanks.谢谢。

No need for a hack with variables (which don't exist in standard SQL or Postgres to begin with).不需要对变量进行破解(标准 SQL 或 Postgres 中不存在)。

This can easily be done using a window function.这可以使用 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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM