Why `GROUP BY` in hook_views_query_alter() doesn't work? I'm using Views 7.x-3.6 and I tried altering the GROUP BY clause with hook_views_query_alter() as below:

function mymodule_views_query_alter(&amp;$view, &amp;$query) {
    if ($view-&gt;name == "view_name"){
      $query-&gt;add_groupby('field_name');
      dpm($query);    
    }
}


When I look in $query, the groupby clause is correctly enabled but the SQL query is not affected: the GROUP BY clause doesn't appear:



What I eventually did is using a Drupal core hook (hook_query_alter()) and it worked fine: the SQL is now affected.

function mymodule_query_alter(QueryAlterableInterface $query) {
  $view_name = 'view_name';
  if ($query-&gt;hasTag('views_' . $view_name)) {    
    $query-&gt;groupBy('field_name');
  }
}


Any reason why my hook_views_query_alter() doesn't work? I'm wondering if there's a cleaner way to do it and.
Use add_field() with array('function' =&gt; 'groupby') parameter.

$query-&gt;add_field('node', 'nid', 'node_nid', array('function' =&gt; 'groupby'));
$query-&gt;add_groupby('node.nid');


Aditional information:

After using add_groupby you might see the next code after GROUP BY:

GROUP BY node.nid, nid


See the next issue: https://drupal.org/node/1578808

To avoid unnecessary GROUP BY conditions add:

$query-&gt;distinct = TRUE;