Postgres column aliases for computed values

I tried using aliases in postgres for this request, but postgres stops and complains that ERROR: column "subtotal" does not exist

SELECT SUM(price) AS subtotal, subtotal * 3.0 AS fees, (subtotal + fees) AS total FROM cart 

You cannot use aliases as part of the next column?

+4
source share
2 answers

No, you cannot reuse a column alias within a single SQL statement - use:

 SELECT SUM(t.price) AS subtotal, SUM(t.price) * 3.0 AS fees, SUM(t.price + fees) AS total FROM CART t 

You can reference a column alias in an ORDER BY clause, some databases also support links in GROUP BY and HAVING .

+5
source

Question about your answer:

  SELECT SUM(t.price) AS subtotal, SUM(t.price) * 3.0 AS fees, SUM(t.price + fees) AS total FROM CART t 

If it is not, if you cannot reuse the column alias within the same SQL statement:

  SELECT SUM(t.price) AS subtotal, SUM(t.price) * 3.0 AS fees, SUM(t.price + (t.price * 3.0)) AS total FROM CART t 
0
source

Source: https://habr.com/ru/post/1310310/


All Articles