SQL Oracle中的减号查询

时间:2018-12-27 11:29:57

标签: jquery sql oracle oracle11g oracle-sqldeveloper

我试图从两个表中减去两个float值:

第一个是:

select sum (cost) as "total cost" from (SELECT * 
FROM PRODUCT 
LEFT JOIN sell_bill ON sell_bill.PRODUCT_ID=PRODUCT.ID
WHERE (product.cost > sell_bill.PRICE)

它返回240

第二个是:

select sum (price) as "total price" from (SELECT *
FROM PRODUCT 
LEFT JOIN sell_bill ON sell_bill.PRODUCT_ID=PRODUCT.ID
WHERE (product.cost > sell_bill.PRICE)

它返回140

这就是我尝试过的:

select sum (cost) as "total cost" from (SELECT * 
FROM PRODUCT 
LEFT JOIN sell_bill ON sell_bill.PRODUCT_ID=PRODUCT.ID
WHERE (product.cost > sell_bill.PRICE)
minus 
select sum (price) as "total price" from (SELECT *
FROM PRODUCT 
LEFT JOIN sell_bill ON sell_bill.PRODUCT_ID=PRODUCT.ID
WHERE (product.cost > sell_bill.PRICE)
;

但是它返回了240 ...怎么了?

2 个答案:

答案 0 :(得分:2)

MINUS运算符没有达到您的期望:它不减去值,而是对数据集进行操作(返回第一个SELECT语句中所有第二行未返回的行)。

此外,您不需要使用子查询来计算SUM,例如:SELECT SUM(cost) from (SELECT...);我删除了。

我想你只是想要:

SELECT 
    SUM(cost) - SUM(price)
FROM 
    product 
    LEFT JOIN sell_bill ON sell_bill.product_id = product.id
WHERE product.cost > sell_bill.price

答案 1 :(得分:0)

您可以在下面尝试-

SELECT sum (cost)-sum (price) as difference
FROM PRODUCT 
LEFT JOIN sell_bill ON sell_bill.PRODUCT_ID=PRODUCT.ID
WHERE product.cost > sell_bill.PRICE