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

后端 未结 5 723
故里飘歌
故里飘歌 2020-11-28 07:32

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:

  • Co
5条回答
  •  無奈伤痛
    2020-11-28 08:28

    If you want to refer to calculated column on the "same query level" then you could use CROSS APPLY(Oracle 12c):

    --Sample data:
    CREATE TABLE tab(ColumnA NUMBER(10,2),ColumnB NUMBER(10,2),ColumnC NUMBER(10,2));
    
    INSERT INTO tab(ColumnA, ColumnB, ColumnC) VALUES (2, 10, 2);
    INSERT INTO tab(ColumnA, ColumnB, ColumnC) VALUES (3, 15, 6);
    INSERT INTO tab(ColumnA, ColumnB, ColumnC) VALUES (7, 14, 3);
    COMMIT;
    

    Query:

    SELECT
      ColumnA,
      ColumnB,
      sub.calccolumn1,
      sub.calccolumn1 / ColumnC AS calccolumn2
    FROM tab t
    CROSS APPLY (SELECT t.ColumnA + t.ColumnB AS calccolumn1 FROM dual) sub;
    

    DBFiddle Demo


    Please note that expression from CROSS APPLY/OUTER APPLY is available in other clauses too:

    SELECT
      ColumnA,
      ColumnB,
      sub.calccolumn1,
      sub.calccolumn1 / ColumnC AS calccolumn2
    FROM tab t
    CROSS APPLY (SELECT t.ColumnA + t.ColumnB AS calccolumn1 FROM dual) sub
    WHERE sub.calccolumn1 = 12;
    -- GROUP BY ...
    -- ORDER BY ...;
    

    This approach allows to avoid wrapping entire query with outerquery or copy/paste same expression in multiple places(with complex one it could be hard to maintain).

    Related article: The SQL Language’s Most Missing Feature

提交回复
热议问题