简体   繁体   中英

subtract two different sum of column from two different table in select query

I have two tables with the name of add_sell and add_expense. I have inserted some of value into the tables. I wanted to get the total profit result. I did it myself but the result is showing 0 . Now how can I do that. I also give the total profit formula. Is anyone here to help me? Here is the code given below

function totalSell(){
    global $conn;
    $sql = "SELECT SUM(`sell_amount`) as 'Sumearning' FROM `add_sell` WHERE sell_amount = `sell_amount`";
        $result = $conn->query($sql);
        $getDate = date('d/m/Y');                    
        if(mysqli_num_rows($result) > 0){

        while($fetch = mysqli_fetch_array($result)){                  
        echo "SR ".$fetch['Sumearning']; 
       }
    }
}

function totalExpense(){
    global $conn;
    $ex = "SELECT SUM(`expense_amount`) as `Sumexpense` FROM `add_expense` WHERE expense_amount = `expense_amount` ";
    $run_ex = $conn->query($ex);
    if (mysqli_num_rows($run_ex) > 0) {
        while ($tex = mysqli_fetch_array($run_ex)) {
        echo "SR ".$tex['Sumexpense'];
        }
    }
}

function totalProfit(){

    global $conn;

    $sql = "SELECT SUM(`sell_amount`) as 'Sumearning' FROM `add_sell` WHERE sell_amount = `sell_amount`";
        $result = $conn->query($sql);
        $getDate = date('d/m/Y');
        while($fetch = mysqli_fetch_array($result)){                  
            $fetch['Sumearning']; 
            echo "Total Earning : ".$totalEarning = "SR ".$fetch['Sumearning']; 
       }

$ex = "SELECT SUM(`expense_amount`) as `Sumexpense` FROM `add_expense` WHERE expense_amount = `expense_amount` ";
        $run_ex = $conn->query($ex);

        while ($tex = mysqli_fetch_array($run_ex)) {
            $tex['Sumexpense'];
            echo "Total Expense : ".$totlaExpenss = "SR ".$tex['Sumexpense'];
        }
        echo "Your totla Profit is : ".$totalprofit = $totalEarning - $totlaExpenss;
}

Do you mean getting the difference between the Sum earnings and the Sum expenses? Because you can do it like this?

$Total = $tex['Sumexpense'] - $fetch['Sumearning'];

Echo $total;

Total profit result you can get from query itself.

$sql = "SELECT SUM(`sell_amount`)-(SELECT SUM(`expense_amount`) FROM `add_expense` WHERE expense_amount = `expense_amount`)  AS `PROFITLOSS` FROM `add_sell` WHERE sell_amount = `sell_amount`";

Note: as Sumearning and as Sumexpense Removed instead you will get as PROFITLOSS

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