QueryGroup group = new QueryGroup();
for (AbstractColumn col : newGroupColumns) {
group.addColumn(col);
}
dataSourceQuery.setGroup(group);
QuerySelection selection = new QuerySelection();
for (AbstractColumn col : newSelectionColumns) {
selection.addColumn(col);
}
dataSourceQuery.setSelection(selection);
// Build the completion query to group by the grouping columns. Because an aggregation is
// required, make a dummy aggregation on the original column by which the aggregation is
// required.
// This original column must be unique for a given set of values for the grouping/pivoting
// columns so any aggregation operation out of MIN, MAX, AVG will return the value
// itself and will not aggregate anything. The example from before,
// SELECT A, max(B) GROUP BY A PIVOT C turns into SELECT A, min(max-B) GROUP BY A PIVOT C
completionQuery.copyFrom(query);
completionQuery.setFilter(null);
QuerySelection completionSelection = new QuerySelection();
List<AbstractColumn> originalSelectedColumns =
query.getSelection().getColumns();
for (int i = 0; i < originalSelectedColumns.size(); i++) {
AbstractColumn column = originalSelectedColumns.get(i);
if (query.getGroup().getColumns().contains(column)) {
completionSelection.addColumn(column);
} else { // Must be an aggregation column if doesn't appear in the grouping.
// The id here is the id generated by the data source for the column containing
// the aggregated data, e.g., max-B.
String id = column.getId();
// MIN is chosen arbitrarily, because there will be exactly one.
completionSelection.addColumn(
new AggregationColumn(new SimpleColumn(id), AggregationType.MIN));
}
}
completionQuery.setSelection(completionSelection);