如何在Laravel中按会员与年份分组聚合金额?
Laravel Eloquent 分组汇总金额问题
现有members表数据
| member | Year | Amount |
|---|---|---|
| Vinoth | 2015 | 1000 |
| Vinoth | 2016 | 1000 |
| Vinoth | 2016 | 300 |
| Prabu | 2015 | 1000 |
| Prabu | 2016 | 1000 |
| Ravanan | 2016 | 100 |
| Vinoth | 2016 | 3000 |
| Vinoth | 2016 | 3000 |
预期查询结果
需要按会员+年份分组,汇总对应金额,得到如下结果:
| member | Year | Amount |
|---|---|---|
| Vinoth | 2015 | 1000 |
| Vinoth | 2016 | 7300 |
| Prabu | 2015 | 1000 |
| Prabu | 2016 | 1000 |
| Ravanan | 2016 | 100 |
已尝试的代码
Member::select('SUM(amount) as amount', 'year', 'member')->groupby('year')->get();
解决方法
你的代码问题在于仅按year分组,但我们需要同时按member和year两个字段分组,才能实现会员+年份的组合汇总。另外,Laravel中直接在select里写聚合函数需要用DB::raw()或者selectRaw()来解析SQL表达式。
正确代码示例:
方法一:使用selectRaw
Member::selectRaw('member, year, SUM(amount) as total_amount') ->groupBy('member', 'year') ->get();
方法二:使用DB::raw
use Illuminate\Support\Facades\DB; Member::select( 'member', 'year', DB::raw('SUM(amount) as total_amount') ) ->groupBy('member', 'year') ->get();
说明:
- 分组字段必须包含所有非聚合的查询字段(这里就是
member和year),否则会违反SQL的分组规则。 - 可以将汇总后的字段名改为
total_amount(也可保持amount),更清晰区分原始字段和汇总结果。 - 如果Laravel开启了严格模式(默认开启),确保
groupBy包含所有非聚合字段,避免SQL报错。
内容的提问来源于stack exchange,提问作者cantida
相关产品推荐
相关产品推荐

