我有一个表total_count
id studid month year acls_id total_p total_a
1 30 08 2015 12 5 2
2 35 08 2015 12 5 2
3 52 08 2015 12 5 2
4 53 08 2015 12 5 2
5 54 08 2015 12 5 2
6 55 08 2015 12 5 2
7 30 09 2015 12 3 0
8 35 09 2015 12 3 0
9 52 09 2015 12 2 1
10 53 09 2015 12 3 0
11 54 09 2015 12 3 0
12 55 09 2015 12 3 0
我想计算每个学生的 total_p
和 total_a
。
例如:studid = 30
、total_p = 5
和 total_a = 2
。
因此,我想获取每个studid
的每月总计以及总月份的total_p
和total_a
总和.
我的 Controller 代码是
$total_counts = DB::table('total_count')
->whereBetween('smonth',08, 09))
->whereBetween('syear', 2015, 2015))
->sum('total_p);
->sum('total_a);
查看blade.php
{{$total_counts->total_p}}
{{$total_counts->total_a}}
但它不起作用..
如何在查询生成器格式中使用 sum()
?
我想要这样的输出:
studid total_p total_a
30 8 2
35 8 2
52 7 3
53 8 2
54 8 2
55 8 2
最佳答案
Eloquent 的聚合函数 sum() 为所有匹配条件的行返回一个标量。如果您想要获取行列表,则需要构建一个查询,根据学生的 ID 对学生进行分组并计算每个学生的总和。
这个查询应该可以解决问题:
$total_counts = DB::table('total_count')
->whereBetween('smonth',08, 09))
->whereBetween('syear', 2015, 2015))
->groupBy('studid')
->get(['studid', DB::raw('SUM(total_a) AS sum_a'), DB::raw('SUM(total_p) AS sum_p')]);
$total_counts 中的每一行将包含 3 个值:studid、sum_a 和 sum_p。
关于php - 如何在 Laravel 中使用 sum(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32094612/