--- views_query.inc.unhacked	2007-04-12 18:18:59.000000000 +0300
+++ views_query.inc	2007-06-05 01:57:44.000000000 +0300
@@ -621,6 +621,24 @@
 
       // we only add the groupby if we're not counting.
       if ($this->groupby) {
+      	//Make fscking sure we've all selected fields in group by to avoid breaking PostgreSQL.
+      	//
+      	//$this->field already has aliases and other cruft. Get rid of 'em first.
+      	//Besides, we should omit fields that are just aggregate functions.
+      	//
+				//First, get rid of aliases.
+				$groupbyfields = preg_replace('/\ AS.*/', '', $this->fields);
+				//If selection is surroundend by DISTINCT, get rid of it.
+				$groupbyfields = preg_replace('/DISTINCT\(/', '', $groupbyfields);
+				$groupbyfields = preg_replace('/\)/', '', $groupbyfields);
+				//If we still have opening parenthesis, the field is an aggregate function.
+				//Drop it altogether!
+				$groupbyfields = preg_grep('/.*\(/', $groupbyfields, PREG_GREP_INVERT);
+      	foreach($groupbyfields as $field) {
+      		if (!(in_array($field, $this->groupby))) {
+  	        $this->add_groupby($field);
+	        }
+      	}
         $groupby = "GROUP BY " . implode(', ', $this->groupby);
       }
 
