【问题标题】:Laravel collection sum of columns group by monthLaravel按月分组的列集合总和
【发布时间】:2019-07-05 14:48:47
【问题描述】:

我正在处理 Laravel 项目,我需要获取一些数据,对各列求和并将结果分组为 M-y(1 月 19 日)格式以显示在每月条形图中。

我能够成功地对数据进行汇总和分组,但问题是,对于没有任何记录的月份,我仍然希望以总数等于 0 的方式显示在图表中。

这是我目前的做法:

$data = $this->user->income()
              ->whereBetween('game_date', ['2019-01-01', '2019-04-30'])
              ->selectRaw('sum(total_score) as score,
                           sum(total_stars) as stars,
                           MONTH(game_date) as month,
                           DATE_FORMAT(game_date,"%b") as month_name
                          ')
              ->groupBy('month', 'month_name')
              ->get();

这给了我以下结果(缺少没有任何记录的月份):

[    
    {
        "score": "707",
        "stars": "64",
        "month": 1,
        "month_name": "Jan"
    },
    {
        "score": "200",
        "stars": "29",
        "month": 3,
        "month_name": "Mar"
    }
]

并且预期的结果是包括缺少月份以使图表清晰可见:

[
    {
        "score": "707",
        "stars": "64",
        "month": 1,
        "month_name": "Jan"
    },
    {
        "score": "0",
        "stars": "0",
        "month": 2,
        "month_name": "Feb"
    },
    {
        "score": "200",
        "stars": "29",
        "month": 3,
        "month_name": "Mar"
    },
]

请注意,->whereBetween('game_date', []) 将离开的日期从月初到月底(涵盖完整的月度记录)。

【问题讨论】:

    标签: laravel eloquent laravel-5.6 laravel-collection


    【解决方案1】:

    你必须使用 COALESCE() 函数。这是因为在 2 月份,您在 sum(total_score) 作为分数 处得到 null,而不是 0。看看

    herehere

    帮帮忙

    【讨论】:

    • 返回相同的结果。我认为因为 2 月份没有日期记录,所以它不能按 2 月份分组。
    • 还有其他解决方案吗?
    猜你喜欢
    • 2021-03-08
    • 2019-06-28
    • 2016-12-07
    • 1970-01-01
    • 2017-04-24
    • 1970-01-01
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    相关资源
    最近更新 更多