Tuesday, March 21, 2017

groupBy and orderBy Laravel for getting higher value

I have problem when grouping and ordering the result of my query. here is my data

+--------+-----------+----------+--------+-------+
| id_krs | id_mhs_pt | id_kelas | status | nilai |
+--------+-----------+----------+--------+-------+
|     38 | 3         |  29      | B      | A     |
|     45 | 3         |  30      | B      | A     |
|     46 | 3         |  31      | B      | C     |
|  18393 | 3         |  31      | U      | A     |
+--------+-----------+----------+--------+-------+

here is my query

DB::table('krs')->select('id_krs','id_kelas','status','nilai')
    ->where('id_mhs_pt',3)->groupBy('id_kelas')->orderBy('nilai','asc')->get();

when i run the query, the result is:

+--------+-----------+----------+--------+-------+
| id_krs | id_mhs_pt | id_kelas | status | nilai |
+--------+-----------+----------+--------+-------+
|     38 | 3         |  29      | B      | A     |
|     45 | 3         |  30      | B      | A     |
|     46 | 3         |  31      | B      | C     |
+--------+-----------+----------+--------+-------+

and the result i want is

+--------+-----------+----------+--------+-------+
| id_krs | id_mhs_pt | id_kelas | status | nilai |
+--------+-----------+----------+--------+-------+
|     38 | 3         |  29      | B      | A     |
|     45 | 3         |  30      | B      | A     |
|  18393 | 3         |  31      | U      | A     |
+--------+-----------+----------+--------+-------+

Because the id_krs 18393 have greater nilai (score) than id_krs 46 (both using same id_kelas). I tried to change the order to asc or desc, but the result still the same. How to get that? Thank's!



via Eggy Endeska

Advertisement