diff --git a/mysql-test/r/order_by.result b/mysql-test/r/order_by.result
index 15643f29513b8216fda4c5ac6478320d85e97db7..abc48783cf4a161516071c0a4f5d3a30521b44a3 100644
--- a/mysql-test/r/order_by.result
+++ b/mysql-test/r/order_by.result
@@ -733,3 +733,10 @@ xxxxxxxxxxxxxxxxxxxaa
 xxxxxxxxxxxxxxxxxxxx
 xxxxxxxxxxxxxxxxxxxz
 drop table t1;
+create table t1 (a int not null, b  int not null, c int not null);
+insert t1 values (1,1,1),(1,1,2),(1,2,1);
+select a, b from t1 group by a, b order by sum(c);
+a	b
+1	2
+1	1
+drop table t1;
diff --git a/mysql-test/t/order_by.test b/mysql-test/t/order_by.test
index 988c106bf2158bbec70f254398a2b7df1a1b74bb..dd36cd95969537aa84fb2f4f8feb31c7b60b6974 100644
--- a/mysql-test/t/order_by.test
+++ b/mysql-test/t/order_by.test
@@ -500,3 +500,9 @@ insert into t1 set a = concat(repeat('x', 19), 'aa');
 set max_sort_length=20;
 select a from t1 order by a;
 drop table t1;
+
+create table t1 (a int not null, b  int not null, c int not null);
+insert t1 values (1,1,1),(1,1,2),(1,2,1);
+select a, b from t1 group by a, b order by sum(c);
+drop table t1;
+
diff --git a/sql/sql_select.cc b/sql/sql_select.cc
index 4c652ee972ac663b2a5703adeb654e41c9f1cd89..792083350afdf8d1758cd111c76c43bec26c3771 100644
--- a/sql/sql_select.cc
+++ b/sql/sql_select.cc
@@ -262,11 +262,13 @@ inline int setup_without_group(THD *thd, Item **ref_pointer_array,
 
   save_allow_sum_func= thd->allow_sum_func;
   thd->allow_sum_func= 0;
-  res= (setup_conds(thd, tables, conds) ||
-        setup_order(thd, ref_pointer_array, tables, fields, all_fields,
-                    order) ||
-        setup_group(thd, ref_pointer_array, tables, fields, all_fields,
-                    group, hidden_group_fields));
+  res= setup_conds(thd, tables, conds);
+  thd->allow_sum_func= save_allow_sum_func;
+  res= res || setup_order(thd, ref_pointer_array, tables, fields, all_fields,
+                          order);
+  thd->allow_sum_func= 0;
+  res= res || setup_group(thd, ref_pointer_array, tables, fields, all_fields,
+                          group, hidden_group_fields);
   thd->allow_sum_func= save_allow_sum_func;
   DBUG_RETURN(res);
 }
@@ -11330,7 +11332,7 @@ int setup_order(THD *thd, Item **ref_pointer_array, TABLE_LIST *tables,
    setup_group()
    thd			Thread handler
    ref_pointer_array	We store references to all fields that was not in
-			'fields' here.   
+			'fields' here.
    fields		All fields in the select part. Any item in 'order'
 			that is part of these list is replaced by a pointer
 			to this fields.