如何在select查询中编写一个使用外表进行计算的子查询,我们可以用调整的方式编写它

时间:2015-12-17 05:48:57

标签: sql oracle-sqldeveloper

3表产品,销售,折扣。

create table Product (Pid Varchar2(15),Productname Varchar2(50),PriceofSingle Number(10));
Create table Disc_product(pid varchar2(15),Qty number,disc_percent number);
create table sales(salesid number(20),Pid varchar2(15),productname varchar2(40) ,qty number(10));

想要检索产品的详细信息。如果购买的产品数量超过disc_product表中提供的数量,则折扣百分比适用,否则为否。

我写的查询工作正常.....但它非常凌乱.... 我想要有任何其他方式来实现相同的..

Select  s.salesid,s.pid,p.Productname,s.qty ,
    (NVL((select disc_percent from disc_product where pid = s.pid and qty <s.qty),1)) as disc, 
    ((p.priceofsingle * s.qty ) * (NVL((select disc_percent from disc_product where pid = s.pid and qty <s.qty),1) )) as T_price** 
from sales s left join product p on S.pid = p.pid

1 个答案:

答案 0 :(得分:0)

我会在你的Disc_product表中添加一个qtymin和qtymax。然后,您可以执行LEFT JOIN以匹配值之间的折扣。否则,您将显示包含所有折扣层的重复行。

SELECT  
s.salesid,
s.pid,
p.productname,
s.qty,
NVL(d.disc_percent,1), 
p.priceofsingle * s.qty * NVL(d.disc_percent,1) as T_price
FROM sales s
LEFT JOIN Product p
ON s.pid = p.pid
LEFT JOIN Disc_Product d
ON s.pid = d.pid AND s.qty >= d.qtymin AND s.qty < d.qtymax;