How to use SQL clause GROUP BY?
You can do this to make it work:

$db = \Drupal::database();
$query = $db-&gt;select('sinica_grade_summary','sgs');
$query-&gt;fields('sgs', ['coursename']);
$query-&gt;condition('sgs.uid', $id, '=');
$query-&gt;groupBy("sgs.coursename");