Remove GroupBy field from Drupal View SQL

The views module allows administrators and site designers to create, manage, and display lists of content. Each list managed by the views module, and the output of a view is known as a "display".

However, sometimes the results don't match with our needs and we need to modify the SQL to output the results as per our requirements. This can be done using the various hooks provided by Drupal views. To modify the query, most popular among them is the query_alter hook which enables the user to make changes to the query that is being executed.

I've been in a case where the groupBy clause wasn't included in the $view or the $query object passed to this hook. If we need to change or remove any groupBy field from the query, post_build hook consists of the actual query which will be considered by the view to output the result and the $view object can be used to make the modification to the query. This hook is called after the query is fully built but has not executed yet.

To remove any groupBy column from the view query -

/**
* Implement hook_views_post_build(&$view).
*/
function module_views_post_build(&$view) {
  if ($view->name == 'my_view') {
    //get groupby clause included in the view query
    $grpBy = &$view->build_info['query']->getGroupBy();
    unset($grpBy['field_name']);
  }
}

This hook can also be used to add any fields to groupBy or make any other SQL modifications.