Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a calculated column to calculate another column in the same view

Tags:

sql

oracle

I am hoping you can help with this question. I am using Oracle SQL (SQL Developer for this view)...

If I have a table with the following columns:

  • ColumnA (Number)
  • ColumnB (Number)
  • ColumnC (Number)

In my view I have

Select   ColumnA, ColumnB, ColumnA + ColumnB As calccolumn1 

Now at this point, I want to use calccolumn1 but I cannot just say...

Select   ColumnA, ColumnB, ColumnA + ColumnB As calccolumn1 calccolumn1 / ColumnC as calccolumn2 

I am assuming I need some type of subquery..but this is where I need your help... How would I word the query so that I can use calccolumn1 in another calculation within the same query? It might be an If then or a Case when, but bottomline it is some derived number.

like image 687
Ewaver Avatar asked Oct 04 '13 15:10

Ewaver


People also ask

Can you use a calculated field in another calculated field?

About Calculated Fields 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 a calculated column reference another table?

A computed column may only reference other columns in the same table.

Can you reference a measure in a calculated column?

We can create a calculated column to reference a measure value like this: Column1= <measure name>. But you need to note the calculated column values are calculated based on table context so it's fixed. To do further calculation, you can use measure directly without creating additional calculated column.

How would you add 2 columns on a list in a calculated field?

In the Available site columns box, select the columns to add to the list, and then click Add. Note: If the calculated site column that you are adding contains other site columns, you must add them to the list.


Video Answer


1 Answers

You could use a nested query:

Select   ColumnA,   ColumnB,   calccolumn1,   calccolumn1 / ColumnC as calccolumn2 From (   Select     ColumnA,     ColumnB,     ColumnC,     ColumnA + ColumnB As calccolumn1   from t42 ); 

With a row with values 3, 4, 5 that gives:

   COLUMNA    COLUMNB CALCCOLUMN1 CALCCOLUMN2 ---------- ---------- ----------- -----------          3          4           7         1.4 

You can also just repeat the first calculation, unless it's really doing something expensive (via a function call, say):

Select   ColumnA,   ColumnB,   ColumnA + ColumnB As calccolumn1,   (ColumnA + ColumnB) / ColumnC As calccolumn2 from t42;      COLUMNA    COLUMNB CALCCOLUMN1 CALCCOLUMN2 ---------- ---------- ----------- -----------          3          4           7         1.4  
like image 187
Alex Poole Avatar answered Oct 19 '22 14:10

Alex Poole