简体   繁体   中英

Minus query in SQL Oracle

I was trying to do subtract between two of single float value from two tables:

The first one is:

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)

It returns 240 .

The second one is:

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)

It returns 140 .

So this is what I tried:

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)
;

But it returned 240 ... What's wrong?

The MINUS operator does not do what you expect: it does not substract values, it operates on datasets (return all rows in the first SELECT statement that are not returned by the second SELECT statement).

Also, you don't need to use a subquery to compute the SUM , like: SELECT SUM(cost) from (SELECT... ); I removed it.

I guess that you just want:

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

You can try below -

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

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