Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PostgreSQL Views: Referencing one calculated field in another calculated field

I have the same question as #1895500, but with PostgreSQL not MySQL.

How can I define a view that has a calculated field, for example:

 (mytable.col1 * 2) AS times_two

... and create another calculated field that's based on the first one:

 (times_two * 2) AS times_four

...?

like image 630
6 revs, 4 users 74% Avatar asked Mar 05 '10 09:03

6 revs, 4 users 74%


People also ask

Can you use a calculated field in another calculated field?

A calculated field becomes a new field in the pivot table, and its calculation can use the sum of other fields. Calculated fields appear with the other value fields in the pivot table.

Can you do calculations in postgresql?

So, the short answer is that you can't, and that is by design. The notable exception to this is Microsoft Access, where you can indeed use calculations in subsequent columns and WHERE clauses.


1 Answers

Depending on how heavy the formla is, you could use a subquery:

select inner.*, times_two * 2 from
(select mycol * 2 as times_two from table) sub

Or rewrite the computation:

select mycol * 2, mycol * 2 * 2 from table
like image 105
Konrad Garus Avatar answered Oct 20 '22 15:10

Konrad Garus