简体   繁体   中英

PHP MySQL Select a SUM minus a SUM

I'm trying to run a query like below:

SELECT (SUM(amount) - SUM(refundAmount)) as amount FROM orders WHERE $invoiceFilter AND $websiteFilter

It's getting the sum of the amount column correctly, but it's not subtracting out the refund amount.

What is the correct syntax for a query like this?

You maybe missing something like a reference column to filter the data you need to process. Something like:

SELECT (SUM(amount) - SUM(refundAmount)) AS amount 
FROM orders 
WHERE 
    <a_column> = $invoiceFilter 
    AND <another_column> = $websiteFilter;

try this:

SELECT SUM(amount - refundAmount) AS `amount` 
FROM orders 
WHERE 
    invoice = $invoiceFilter 
    AND website = $websiteFilter;

You can use subqueries in the FROM clause.

SQL:

SELECT amount - refund
FROM (SELECT SUM(amount) as amount
      FROM orders
      WHERE invoice = 'invoiceFilter' AND website = 'websiteFilter') as a,
     (SELECT SUM(refundAmount) as refund
      FROM orders
      WHERE invoice = 'invoiceFilter' AND website = 'websiteFilter') as b;

PHP:

mysql_query("SELECT amount - refund
             FROM (SELECT SUM(amount) as amount
                   FROM orders
                   WHERE invoice = '" . mysql_real_escape_string($invoiceFilter). "'
                   AND website = '" . mysql_real_escape_string($websiteFilter). "') as a,
                  (SELECT SUM(refundAmount) as refund
                   FROM orders
                   WHERE invoice = '" . mysql_real_escape_string($invoiceFilter). "'
                   AND website = '" . mysql_real_escape_string($websiteFilter). "') as b; ");

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