简体   繁体   中英

how to sum in Postgres

I have the data I'm querying

total_a | total_b | sum |
1200       500       ?

this my query

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

my query didn't succeed in summing the alias alias

You cannot reference a column alias in the SELECT where it is defined. The reason is simple: SQL does not guarantee the order of evaluation of expressions in the SELECT .

You can use a CTE, subquery, or repeat the expression:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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