SQL Oracle中的减号查询

问题描述 投票:1回答:2

我试图从两个表中减去两个单个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 ......出了什么问题?

jquery sql oracle oracle11g oracle-sqldeveloper
2个回答
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

2
投票

MINUS运算符没有达到预期的效果:它不会减去值,它会对数据集进行操作(返回第一个SELECT语句中未被第二个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
© www.soinside.com 2019 - 2024. All rights reserved.