如何在 Postgres 中求和
how to sum in Postgres
我有要查询的数据
total_a | total_b | sum |
1200 500 ?
这是我的查询
select
ROUND(SUM(CASE WHEN status= 0 THEN total_budget ELSE 0 END)) AS total_a,
ROUND(SUM(CASE WHEN status= 1 THEN total_sisa_tahun_lalu ELSE 0 END)) AS total_b,
SUM(COALESCE(total_a,0) + COALESCE(total_b,0))
from product
我的查询没有成功求和别名 alias
您不能在 SELECT
定义列别名的地方引用它。原因很简单:SQL 不保证 SELECT
.
中表达式的求值顺序
您可以使用 CTE、子查询或重复表达式:
select ROUND(SUM(CASE WHEN status= 0 THEN total_budget ELSE 0 END)) AS total_a,
ROUND(SUM(CASE WHEN status= 1 THEN total_sisa_tahun_lalu ELSE 0 END)) AS total_b,
SUM(CASE WHEN status = 0 THEN total_budget
WHEN status = 1 THEN total_sisa_tahun_lalu
ELSE 0
END)
from product
我有要查询的数据
total_a | total_b | sum |
1200 500 ?
这是我的查询
select
ROUND(SUM(CASE WHEN status= 0 THEN total_budget ELSE 0 END)) AS total_a,
ROUND(SUM(CASE WHEN status= 1 THEN total_sisa_tahun_lalu ELSE 0 END)) AS total_b,
SUM(COALESCE(total_a,0) + COALESCE(total_b,0))
from product
我的查询没有成功求和别名 alias
您不能在 SELECT
定义列别名的地方引用它。原因很简单:SQL 不保证 SELECT
.
您可以使用 CTE、子查询或重复表达式:
select ROUND(SUM(CASE WHEN status= 0 THEN total_budget ELSE 0 END)) AS total_a,
ROUND(SUM(CASE WHEN status= 1 THEN total_sisa_tahun_lalu ELSE 0 END)) AS total_b,
SUM(CASE WHEN status = 0 THEN total_budget
WHEN status = 1 THEN total_sisa_tahun_lalu
ELSE 0
END)
from product