I表 student_attendance 表字段为(id, studed, attendance)。
:studid考勤
28 1
31 1
32 1
28 1
31 1
32 1
28 1
31 1
32 1
28 1
31 0
32 1
28 0
31 1
32 1
28 1
31 1
32 0
28 1
31 1
32 0
我想要这样的结果
id studid total 1's total 0's
1 28 6 1
2 31 6 1
3 32 5 2
如何分别得到每个学生的总出勤率=1和出勤率=0 ?
例:28 - 6(总编号)。1(0秒)和1(0秒),31 - 6(0秒)。1(0秒)和1(0秒),32 - 5(0秒)。
控制器代码:
foreach($students as $student){
$cunt1 = DB::table($wys_attendence_table)
->where('studid',$student->id)
->where('amonth',$amonth)
->where('ayear',$ayear)
->where('attendence','=',1)
->count();
$cunt0 = DB::table($wys_attendence_table)
->where('studid',$student->id)
->where('amonth',$amonth)
->where('ayear',$ayear)
->where('attendence','=',0)
->count();
//var_dump($cunt1);
//var_dump($cunt0);
}
My view page:
@foreach($stud_attend as $stud_attends)
@if($student->id == $stud_attends->studid)
@if($stud_attends->attendence == 1)
<td>
<font color="green" size="3">p</font>
</td>
@elseif($stud_attends->attendence == 0)
<td>
<font color="red" size="3">a</font>
</td>
@endif
<td>{{ $cunt1 }}</td>
<td>{{ $cunt0 }}</td>
@endif
@endforeach
我从var_dump($cunt0)
, var_dump($cunt1)
中得到正确的答案,但它在视图页面中不起作用。
您可以使用像这样的条件计数
http://sqlfiddle.com/!9/9d3c1/2
SELECT
studid,
sum(attendence = 1) AS `total 1's`,
sum(attendence = 0) AS `total 0's`
FROM
student_atendence
GROUP BY
studid;
我不确定你想在哪里得到你在预期结果中显示的id
,因为一个研究可以在该表中分配许多id。如果您想要最小的一个,您可以添加min(id) AS id
来选择,如http://sqlfiddle.com/#!9/9d3c1/4,但它没有多少真正的意义。
我没有使用Laravel的经验,但似乎有可能传递RAW表达式。比如(只是猜测):
DB::table($wys_attendence_table)
->select(DB::raw('studid, sum(attendence = 1) AS `total1`, sum(attendence = 0) AS `total0`'))
->where('studid',$student->id)
->where('amonth',$amonth)
->where('ayear',$ayear);
(我改变了别名,以便在数组中更好地访问它)
也可以使用if条件