diff --git a/core/modules/views/src/Plugin/views/query/Sql.php b/core/modules/views/src/Plugin/views/query/Sql.php
index 61dbfb7..93fd6e8 100644
--- a/core/modules/views/src/Plugin/views/query/Sql.php
+++ b/core/modules/views/src/Plugin/views/query/Sql.php
@@ -1236,6 +1236,9 @@ public function query($get_count = FALSE) {
     if (count($this->having)) {
       $this->hasAggregate = TRUE;
     }
+    elseif ($this->has_aggregate == FALSE) {
+      $this->hasAggregate = $this->view->display_handler->getOption('group_by');
+    }
     $groupby = array();
     if ($this->hasAggregate && (!empty($this->groupby) || !empty($non_aggregates))) {
       $groupby = array_unique(array_merge($this->groupby, $non_aggregates));
@@ -1266,6 +1269,9 @@ public function query($get_count = FALSE) {
     // Add groupby.
     if ($groupby) {
       foreach ($groupby as $field) {
+        if ($this->fields[$field]['table'] == NULL && $this->count_field['field'] != $this->fields[$field]['field']) {
+          continue;
+        }
         $query->groupBy($field);
       }
       if (!empty($this->having) && $condition = $this->buildCondition('having')) {
