从选择查询中的两个不同表中减去两个不同的列总和

时间:2019-05-31 10:33:32

标签: php mysql sql

我有两个名为add_sell和add_expense的表。 我已经在表中插入了一些价值。我想获得总利润结果。我自己做了,但结果显示为0。现在我该怎么做。我还给出了总利润公式。有人在这里帮助我吗?这是下面给出的代码

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

2 个答案:

答案 0 :(得分:0)

您是说要获得总收入和总支出之间的差额吗? 因为你可以这样吗?

  

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

     

回声$ total;

答案 1 :(得分:0)

您可以从查询本身获得的总利润结果。

$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`";

请注意:以SumearningSumexpense的形式删除,您将获得“利润”