我正在使用查询来计算每个月的列总和,问题是当我获取数据并且一个月没有数据时,该月没有行,那么我不知道哪个是哪个月份,如果月份金额为0,则返回0会很有帮助, 这是查询:
$test = DB::table('actuals')
->Where('company_id',$id)
->Where('account_level_l','LIKE','%Income%')
->select(DB::raw('SUM(amount) as total_amount'))
->groupBy(DB::raw('MONTH(date) ASC'))->get();
这是返回的对象,从12个月10开始有数据:
Collection {#1381 ▼
#items: array:10 [▼
0 => {#1370 ▼
+"total_amount": 133409.46
}
1 => {#1371 ▼
+"total_amount": 77421.36
}
2 => {#1372 ▼
+"total_amount": 78193.81
}
3 => {#1373 ▼
+"total_amount": 940477.66
}
4 => {#1374 ▼
+"total_amount": 81713.1
}
5 => {#1375 ▼
+"total_amount": 64792.43
}
6 => {#1376 ▼
+"total_amount": 85099.41
}
7 => {#1377 ▼
+"total_amount": 127753.07
}
8 => {#1378 ▼
+"total_amount": 62953.11
}
9 => {#1379 ▼
+"total_amount": 356.61
}
]
}
答案 0 :(得分:-1)
您只需要像这样选择查询中的月份号:
$test = DB::table('actuals')
->Where('company_id',$id)
->Where('account_level_l','LIKE','%Income%')
->select(DB::raw('SUM(amount) as total_amount, MONTH( date ) as month'))
->groupBy(DB::raw('MONTH(date) ASC'))->get();
这将给出每一行的number of month
和total_amount