I've got a view that is showing duplicates and want to easily just modify the query generated by views to group by a specific field. Looking at the query that views creates, I can easily accomplish this by just adding a group by on a specific field, which in this case is not a field that is specified as a field in the Views UI.

It would seem that you should be able to just do a hook_views_query_alter() to adjust the query I need. This is what I did:

function hook_views_query_alter(&$view, &$query) {
  // I only know of this field alias by viewing the query views creates, I did not explicitly add this field.
  $query->add_groupby('myfield_alias'); 
}

Unfortunately views does not respect adding a groupby like this due to requiring HAVING aggregates. I modified views_plugin_query_default.inc to allow this groupby without aggregates. GROUP BY statements do not require aggregates, views shouldn't either. I also added a ternary for setting the fields to groupby.

Patch to come in the comments.

Comments

tom friedhof’s picture

StatusFileSize
new796 bytes

Attaching a patch.

merlinofchaos’s picture

Status: Active » Closed (won't fix)

You're wrong. The presence of GROUP BY according to ANSI sql requires all fields in the SELECT to either be aggregate or in the GROUP BY.

This is the intended behavior; otherwise, pgsql queries break using group by.

tom friedhof’s picture

Category: bug » support
Status: Closed (won't fix) » Active

Ahh, that's good to know. Thanks for clearing that up and responding so quickly to the issue.

Changing this issue over to a support request. What is the best way for adding a GROUP BY statement to a query that views creates?

merlinofchaos’s picture

Status: Active » Fixed

I guess you could go through the fields and set the flag that will trick Views into believing it's an aggregate. Obviously that will only work on MySQL but chances are that's what you're using anyway.

Status: Fixed » Closed (fixed)

Automatically closed -- issue fixed for 2 weeks with no activity.

Anonymous’s picture

Issue summary: View changes

wrote the wrong hook function