Laravel 按日期分组,如 MySQL 查询 GROUP BY MONTH(fields) [关闭]

Posted

技术标签:

【中文标题】Laravel 按日期分组,如 MySQL 查询 GROUP BY MONTH(fields) [关闭]【英文标题】:Laravel group by date like MySQL query GROUP BY MONTH(fields) [closed] 【发布时间】:2021-06-29 17:36:26 【问题描述】:

如何选择 no_inv、total_unpaid、total_paid with order per monthsum(total_unpaid & total_paid)在 Laravel Query Builder 中获取更多信息,我正在使用 Laravel 8。

我对这个双重查询及其条件感到困惑

发票表:

no_inv | date_inv   | total_unpaid | total_paid | note
INV-1  | 2021-01-01 | 100          | 50         | Half Payment of Invoice :
INV-2  | 2021-01-02 | 200          | 0          | Bill of :
INV-3  | 2021-01-03 | 300          | 200        | Half Payment of Invoice :
INV-4  | 2021-02-01 | 400          | 400        | Full Payment of Invoice :
INV-5  | 2015-02-02 | 500          | 400        | Half Payment of Invoice :
The results I expected :
2021-01-01 | Bill of INV-1 `before the total paid` | (-100) `total_unpaid`
2021-01-01 | Half Payment of Invoice : INV-1 `if total_paid > 0 will double column payment like this same as above` | (+50) `total_unpaid`

2021-01-02 | Bill of : INV-2 `if total_paid < 0 not double column as above` | (-200)

2021-01-03 | Bill of INV-3  | (-400) |
2021-01-03 | Bill of INV-3  | (+200) |

2021-02-01 | Bill of INV-4  | (-400) |
2021-02-01 | Full Payment of INV-4  | (+400) |

2015-02-02 | Bill of INV-5 | (-500)
2015-02-02 | Half Payment of INV-5 | (+500)

【问题讨论】:

【参考方案1】:

试试这个

DB::table('invoice')
->select('no_inv','date_inv',DB::raw('Month(date_inv) AS month'),DB::raw('SUM(total_unpaid) AS unpaid'),DB::raw('SUM(total_paid) AS paid'))
->groupBy('month','no_inv','date_inv')
->take(3)
->get();

【讨论】:

Illuminate\Database\QueryException: SQLSTATE[42000]: 语法错误或访问冲突:1140 没有 GROUP 的 GROUP 列 (MIN(),MAX(),COUNT(),...) 的混合如果没有 GROUP BY,则列是非法的 我收到了那个错误 检查答案我已经更新了 它有效,但它并没有解决我的问题,因为我想在每年和每月的同一时期总结已付和未付 好的再试一次我已经更新了答案【参考方案2】:

您可以使用 eloquent & query builder 来使用组:

GroupBy 使用 Eloquent:

$result = Invoice::select('no_inv', 'date_inv', DB::raw('Month(date_inv) AS month'), DB::raw('SUM(total_unpaid) AS unpaid'), DB::raw('SUM(total_paid) AS paid'))
    ->groupby('month','no_inv', 'date_inv')
    ->orderBy('month', 'ASC')
    ->get();

$result = Invoice::select('no_inv', 'date_inv')
    ->selectRaw('MONTH(date_inv) AS month', 'SUM(total_unpaid) AS unpaid', 'SUM(total_paid) AS paid')
    ->groupby('month','no_inv', 'date_inv')
    ->get();

GroupBy 使用查询生成器:

$result = DB::table('invoice')->select('no_inv', 'date_inv', DB::raw('Month(date_inv) AS month'), DB::raw('SUM(total_unpaid) AS unpaid'), DB::raw('SUM(total_paid) AS paid'))
    ->groupby('month','no_inv', 'date_inv')
    ->orderBy('month', 'ASC')
    ->get();

【讨论】:

以上是关于Laravel 按日期分组,如 MySQL 查询 GROUP BY MONTH(fields) [关闭]的主要内容,如果未能解决你的问题,请参考以下文章

如何使用Laravel按日期分组和统计记录?

MySQL查询根据按月分组的激活日期计算累积用户数

按日期对 MySQL 查询结果进行分组,每个组都有标题和自己的 div

Laravel 每天按奇数小时对数据进行分组

MySQL实现按天分组统计,提供完整日期列表,无数据自动补0

mysql按日期分组(group by)查询统计的时候,没有数据补0的解决办法