Index: includes/database/select.inc
===================================================================
RCS file: /cvs/drupal/drupal/includes/database/select.inc,v
retrieving revision 1.55
diff -u -p -r1.55 select.inc
--- includes/database/select.inc	29 Nov 2010 04:45:10 -0000	1.55
+++ includes/database/select.inc	22 Dec 2010 04:56:33 -0000
@@ -1370,14 +1370,14 @@ class SelectQuery extends Query implemen
       // the GROUP BY clause need to be present in the query.
       $fields =& $count->getFields();
       foreach (array_keys($fields) as $field) {
-        if (!empty($group_by[$field])) {
+        if (empty($group_by[$field])) {
           unset($fields[$field]);
         }
       }
       $expressions =& $count->getExpressions();
       foreach (array_keys($expressions) as $field) {
-        if (!empty($group_by[$field])) {
-          unset($fields[$field]);
+        if (empty($group_by[$field])) {
+          unset($expressions[$field]);
         }
       }
 
Index: modules/simpletest/tests/database_test.test
===================================================================
RCS file: /cvs/drupal/drupal/modules/simpletest/tests/database_test.test,v
retrieving revision 1.106
diff -u -p -r1.106 database_test.test
--- modules/simpletest/tests/database_test.test	22 Dec 2010 01:16:43 -0000	1.106
+++ modules/simpletest/tests/database_test.test	22 Dec 2010 04:56:33 -0000
@@ -1989,6 +1989,25 @@ class DatabaseSelectComplexTestCase exte
     $this->assertEqual($count, 4, t('Counted the correct number of records.'));
   }
 
+
+  /**
+   * Test that countQuery properly removes fields and expressions.
+   */
+  function testCountQueryFieldRemovals() {
+    // countQuery should remove all fields and expressions, so this can be
+    // tested by adding a non-existant field: if the non-existant field ends
+    // up in the query, it will throw an error. If not, it will return the
+    // number of records, which in this case happens to be 4 (there are four
+    // records in the {test} table).
+    $query = db_select('test');
+    $query->fields('test', array('fail'));
+    $this->assertEqual(4, $query->countQuery()->execute()->fetchField(), t('Count Query removed fields'));
+
+    $query = db_select('test');
+    $query->addExpression('fail');
+    $this->assertEqual(4, $query->countQuery()->execute()->fetchField(), t('Count Query removed expressions'));
+  }
+
   /**
    * Test that we can generate a count query from a query with distinct.
    */
