When you configure a ContentByQueryWebPart to group and sort data, the data is first sorted on the GroupBy-field and then on the SortBy-field. In my case, I have a webpart grouping by on a field named “Category” and sorted on a field named “SortIndex”. However, I don’t want to sort on Category, only on SortIndex.

The solution: Create a custom webpart, derived from ContentByQueryWebPart, override the OnLoad:

protected override void OnLoad(System.EventArgs e)
  ProcessDataDelegate += this.ProcessData;  

and implement the ProcessData:

private new DataTable ProcessData(DataTable data)
  var sortedField = string.Format("{{{0}}}", Constants.Fields.SortIndex);
  var query = from c in data.AsEnumerable()
                        orderby c.Field<string>(sortedField) ascending
                        select c;
  return query.CopyToDataTable();

Attach a debugger to determine which columns are in the DataTable. It looks like the view-fields are available with their DisplayName; the sortfield was available with it’s Guid.

Extra: Create a custom property to enable/disable this functionality.