Index: openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/SelectImpl.java =================================================================== --- openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/SelectImpl.java (revision 564450) +++ openjpa-jdbc/src/main/java/org/apache/openjpa/jdbc/sql/SelectImpl.java (working copy) @@ -37,6 +37,7 @@ import java.util.Set; import java.util.SortedMap; import java.util.Stack; +import java.util.StringTokenizer; import java.util.TreeMap; import org.apache.commons.collections.iterators.EmptyIterator; @@ -1369,13 +1370,28 @@ groupBy(sql, (Joins) null); } + private boolean columnInGrouping(String col) { + if (_grouping == null) + return false; + + StringTokenizer st = new StringTokenizer(_grouping.getSQL(), + " ,\t\n\r\f"); + while (st.hasMoreTokens()) { + if (StringUtils.equals(st.nextToken(), col)) + return true; + } + return false; + } + public void groupBy(SQLBuffer sql, Joins joins) { getJoins(joins, true); - if (_grouping == null) - _grouping = new SQLBuffer(_dict); - else - _grouping.append(", "); - _grouping.append(sql); + if (!columnInGrouping(sql.getSQL())) { + if (_grouping == null) + _grouping = new SQLBuffer(_dict); + else + _grouping.append(", "); + _grouping.append(sql.getSQL()); + } } public void groupBy(String sql) { @@ -1384,11 +1400,13 @@ public void groupBy(String sql, Joins joins) { getJoins(joins, true); - if (_grouping == null) - _grouping = new SQLBuffer(_dict); - else - _grouping.append(", "); - _grouping.append(sql); + if (!columnInGrouping(sql)) { + if (_grouping == null) + _grouping = new SQLBuffer(_dict); + else + _grouping.append(", "); + _grouping.append(sql); + } } public void groupBy(Column col) { @@ -1396,13 +1414,14 @@ } public void groupBy(Column col, Joins joins) { - if (_grouping == null) - _grouping = new SQLBuffer(_dict); - else - _grouping.append(", "); - PathJoins pj = getJoins(joins, true); - _grouping.append(getColumnAlias(col, pj)); + if (!columnInGrouping(getColumnAlias(col, pj))) { + if (_grouping == null) + _grouping = new SQLBuffer(_dict); + else + _grouping.append(", "); + _grouping.append(getColumnAlias(col, pj)); + } } public void groupBy(Column[] cols) { @@ -1410,16 +1429,15 @@ } public void groupBy(Column[] cols, Joins joins) { - if (_grouping == null) - _grouping = new SQLBuffer(_dict); - else - _grouping.append(", "); - PathJoins pj = getJoins(joins, true); for (int i = 0; i < cols.length; i++) { - if (i > 0) - _grouping.append(", "); - _grouping.append(getColumnAlias(cols[i], pj)); + if (!columnInGrouping(getColumnAlias(cols[i], pj))) { + if (_grouping == null) + _grouping = new SQLBuffer(_dict); + else + _grouping.append(", "); + _grouping.append(getColumnAlias(cols[i], pj)); + } } }