【发布时间】:2019-01-17 11:32:56
【问题描述】:
我需要从我的一个表中获取一组结果以输出到图表。该图表需要显示“本学年(2018 年 9 月 1 日至 2018 年 8 月 31 日)每个月的关注数量”。
返回的结果应该类似于:
| month | total |
|-----------|-------|
| September | 15 |
| October | 23 |
| December | 24 |
| January | 438 |
当我尝试将月份组合在一起时,问题就出现了;我得到一个不正确的计数值。
我目前的查询是:-
// Returns 2018-09-01 00:00:00
$start = Carbon::createMidnightDate(Carbon::now()->subMonths(8)->year, 9, 1);
// Gets current date
$end = Carbon::now();
$concerns = DB::table('concerns')
->select(DB::raw('MONTHNAME(created_at) as month, count(*) as total, created_at'))
->whereBetween('created_at', [$start, $end])
->groupBy('month')
->groupBy('created_at')
->orderBy('created_at', 'asc')
->get()->mapWithKeys(function ($item) {
return [$item->month => $item->total];
});
但是这会返回我:-
| month | total |
|-----------|-------|
| September | 1 |
| October | 1 |
| December | 1 |
| January | 1 |
由于created_at 日期的分组,显然没有将所有单独的值加在一起,但是由于 MySQL only_full_group_by 模式,排除它会阻止我订购它。
任何建议将不胜感激!
【问题讨论】:
标签: mysql laravel group-by sql-order-by