php - 如何使用php和mysql在单循环中计算多个表的每月总和?

标签 php mysql

我在 mysql 数据库中有两个表 Table A 和 Table B

表A

id     date     advanced         payed_remaining        remaining_date
1    1/1/2018     400                 800                   4/1/2018
2    2/1/2018     600                 600                   3/1/2018
3    4/1/2018     800                 200                   6/1/2018
4    6/1/2018     400                 300                   8/1/2018
5    3/2/2018     600                 200                   6/2/2018
6    8/2/2018     800                 400                   10/2/2018

表B

id     date      amount    
1    1/1/2018     900     
2    2/1/2018     600     
3    4/1/2018     300 
4    2/2/2018     400
5    5/2/2018     800 

查询从两个表中获取每月数据,

$monthly_res = $con->prepare("SELECT t2.month, t2.total_advance, t2.total_pay_remaining, t1.total_income_amount FROM (SELECT  month(B.date) as month, SUM(B.income_amount) as total_income_amount FROM B group by month(B.date)) t1 INNER JOIN (SELECT month(A.date) as month, month(A.due_date) as month, t1.total_income_amount, SUM(A.advance) as total_advance, SUM(A.pay_remaining) as total_pay_remaining, t1.total_income_amount FROM A) t2 ON t2.month  = t1.month");
    $monthly_res->execute();
    while ($row = $monthly_res->fetch(PDO::FETCH_ASSOC)) {
        $month = $row['month'];
        $dt = DateTime::createFromFormat('!m', $month);
        $month_name = $dt->format('F');
        $total = $row['total_advance'] + $row['total_income_amount'] + $row['total_pay'];
        echo "<tbody>
            <tr>
                <td>".$month_name."</td>
                <td>".$total."/-</td>
            </tr>
        </tbody>";
    }

1054 - “字段列表”中的未知列“t1.total_income_amount”

当我从查询中删除 t1.total_income_amount 时,它仅显示 12 月的结果...

我想在一个循环中获取每月的预付款总和、payed_remaining 总和、金额总和。

Result= sum(advanced) + sum(payed_remaining) + sum(amount) by month 

January : 5900

February : 3200

最佳答案

你能试试下面的查询吗

SELECT month(A.date) as month, SUM(A.advanced) as total_advance, SUM(A.payed_remaining) as total_pay_remaining, month(B.date) as month, SUM(B.income_amount) as total_income_amount 
From A
join B on month(A.date) = month(B.date)
group by month(A.date)

关于php - 如何使用php和mysql在单循环中计算多个表的每月总和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54266148/

相关文章:

php - 有条件地在 magento 布局中添加 block

mysql - 以原始数据类型从数据库返回值 (Kohana ORM)

MYSQL - 在多表查询中从一列中选择两次

PHP 时间流逝与 MySQL DateTime

php - 结果为左连接和对象的 Symfony2 Doctrine 查询

php - php错误报告也会显示mysql错误吗?

php - 如何使用PHP正确保存MYSQL表中的html内容

php - 无法从值包含中间空格的表中删除条目?

java - 数据库连接在两个应用程序之间共享的对象的整个生命周期内打开

php - 新的 Google ReCaptcha 实现和提交前检查