I am trying to reuse some columns that I compute dynamically in Oracle SQL, something like
SELECT A*2 AS P, P+5 AS Q FROM tablename
Where "tablename" has a column named "A" but no other columns. It gives me
ORA-00904: "P": invalid identifier
I know how to get around this using a subquery like
SELECT P, P+5 AS Q FROM ( SELECT A*2 AS P FROM tablename )
but I think this is ugly. In addition, I want to make the request a little more complicated, for example. reusing "Q" and I do not want to create another subquery.
Update. The reason I want to keep the calculation of “P” is because I want to make it more complex and reuse “P” several times. Therefore, I do not want to explicitly say “A * 2 + 5 AS Q” because it would quickly become cumbersome as “P” becomes more complex.
There must be a good way to do this, any ideas?
Update: I have to note that I am not DB-admin: (.
Update: An example of the real world with a more specific request. I would like to do the following:
SELECT SL/SQRT(AB) AS ALPHA, 5*LOG(10,ALPHA) AS B, 2.5*LOG(10,1-EXP(-5/ALPHA)*(5/ALPHA+1)) AS D BS -2.74 + B + D AS BSA FROM tablename
for now, I wrote this, which works, but ugly:
SELECT SL/SQRT(AB) AS ALPHA, 5*LOG(10,SL/SQRT(AB)) AS B, 2.5*LOG(10,1-EXP(-5/(SL/SQRT(AB)))*(5/(SL/SQRT(AB))+1)) AS D BS -2.74 + 5*LOG(10,SL/SQRT(AB)) + 2.5*LOG(10,1-EXP(-5/(SL/SQRT(AB)))*((5/(SL/SQRT(AB)))+1)) AS BSA FROM tablename
I could do all this after receiving the data, but I thought I would see how much I can allow the database. In addition, I would also like to select “BSA” (what can I do with this request now as a subquery / c-sentence).
Update: OK, I think I’m done now with the solution of Cade Roux and Dave Costa. Although Pax and Jens Schauder solutions would look better, I cannot use them since I am not a database administrator. Now I do not know who should mark the best answer :).
WITH A1 AS ( SELECT A0.*, SL/SQRT(AB) AS ALPHA FROM tablename A0 ), A2 AS ( SELECT A1.*, 5*LOG(10,ALPHA) AS B, 2.5*LOG(10,1-EXP(-5/ALPHA)*((5/ALPHA)+1)) AS D FROM A1 ) SELECT ALPHA, B, D, BS, BS -2.74 + B + D AS BSA FROM A2
BTW, in case someone is interested, SB is the “surface brightness” of galaxies for which B and D are correction members.