ORACLE - Calculate two values and show result in a view

早过忘川 提交于 2019-12-24 10:38:39

问题


I received fantastic help from Dave Costa and Justin Cave here (thanks again) in how to calculate a subtotal value from two other attributes, Quantity and Price (so Quantity * Price = Subtotal). In one of the answers it was stated that from a normalisation point of view it's not good to do this as the subtotal value can be derived from the other two attributes and that I should probably look at using a View. I've read up on Views and am getting the concept (I'll be using them elsewhere regardless) but I'm still not sure how to go about actually calculating the two values and show the result in a custom view. If anyone could point me in the right direction I'd appreciate it.

The current trigger (credit to Dave and Justin):

CREATE VIEW show_subtotal 
AS SELECT price 
FROM products
WHERE product_no =:new.product_no;

:new.subtotal := currentPrice * :new.quantity;


回答1:


Something like this, for example, will compute the subtotal by joining the order_line and product tables together just as the previous trigger was doing. Presumably, you'd want to include some additional attributes (i.e. the order number, the order line number, etc.)

CREATE OR REPLACE VIEW order_line_with_subtotal( product_no,
                                                 quantity, 
                                                 price,
                                                 subtotal )
AS
SELECT ol.product_no,
       ol.quantity,
       p.price,
       (ol.quantity * p.price) subtotal
  FROM order_line ol
       JOIN product p ON (ol.product_no = p.product_no)

This has many of the same data consistency issues that the trigger-based solution had since the current price is being referenced from the product table rather than the then-current price being stored in the order_line table. If you changed the data model so that the order_line table stored the quantity and the current price, the view would get simpler because it would no longer need to join to the product table

CREATE OR REPLACE VIEW order_line_with_subtotal( product_no,
                                                 quantity, 
                                                 price,
                                                 subtotal )
AS
SELECT ol.product_no,
       ol.quantity,
       ol.price,
       (ol.quantity * ol.price) subtotal
  FROM order_line ol

If you are on 11g, you can also create a virtual column in your table definition,

CREATE TABLE order_line (
  order_line_no NUMBER PRIMARY KEY,
  order_no      NUMBER REFERENCES order( order_no ),
  price         NUMBER,
  quantity      NUMBER,
  subtotal      NUMBER GENERATED ALWAYS AS (price*quantity) VIRTUAL 
);


来源:https://stackoverflow.com/questions/8436413/oracle-calculate-two-values-and-show-result-in-a-view

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!