简体   繁体   中英

Is there a way to add a column to a view in ORACLE SQL?

I have a two tables

1.TABLE_STOCK with columns Product_ID (primary key) and Product_unit_price

2.TABLE_SALES with columns Product_ID (foreign key) and Sales_unit_price

Now I wanted to create a view joining the two tables based on Product_ID and add a column PROFIT (which should be the difference between Sales_unit_price and Product_unit_price) to the view.

Is there a way to add a column(PROFIT) to a view?

You can do it as the way you've already described.

CREATE OR REPLACE VIEW V_PRODUCT
AS
   SELECT K.PRODUCT_ID,
      K.PRODUCT_UNIT_PRICE,
      S.SALES_UNIT_PRICE,
      S.SALES_UNIT_PRICE - K.PRODUCT_UNIT_PRICE AS PROFIT
 FROM TABLE_STOCK K
      INNER JOIN TABLE_SALES S ON S.PRODUCT_ID = K.PRODUCT_ID

You can have stock with no sales (but presumably not sales without some stock). Hence, I think you need an outer join :

CREATE OR REPLACE VIEW V_PRODUCT AS
   SELECT st.PRODUCT_ID, st.PRODUCT_UNIT_PRICE,
          s.SALES_UNIT_PRICE,
          (s.SALES_UNIT_PRICE - K.PRODUCT_UNIT_PRICE) AS PROFIT
   FROM TABLE_STOCK st LEFT JOIN
        TABLE_SALES s
        ON S.PRODUCT_ID = st.PRODUCT_ID;

You may need a FULL JOIN , if you can have sales with no stock.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM