Skip to content

Sort GROUP_CONCAT values by the expressions of its ORDER BY #3166

Backlog

Description

@mathiasrw

What happens today

GROUP_CONCAT(x ORDER BY y) sorts by x. The grammar keeps the ORDER BY list as order on the AggrValue. getGroupConcatParams (src/select/groupby.js) passes only the separator and col.order[0].direction on every row. alasql.aggr.GROUP_CONCAT (src/functions/functions.js) sorts the values themselves at stage 3, with localeCompare for two strings, < otherwise, and NULL last.

const people = [{name: 'ann', age: 30}, {name: 'bob', age: 20}, {name: 'cid', age: 25}];
alasql('SELECT VALUE GROUP_CONCAT(name ORDER BY age) FROM ?', [people]);
// 'ann,bob,cid', expected 'bob,cid,ann'

What to change

  1. Resolve col.order with bind.order from Resolve ORDER BY items in one step for plain, grouped and set-operation queries #2693, with the source row as the place. A number n refers to the n-th argument of the aggregate, so ORDER BY 1 is the value itself.
  2. In compileGroup (src/select/groupby.js), compute the keys of each row next to its value. getGroupConcatParams passes the separator once and the array of keys per row. The specification (directions, NULLS FIRST/LAST, COLLATE NOCASE) is passed once when the accumulator is created.
  3. alasql.aggr.GROUP_CONCAT stores {value, keys} pairs and at stage 3 sorts them by the keys, item by item, with ties kept in row order. Move today's GROUP_CONCAT rule (localeCompare for two strings, < otherwise, NULL last) from functions.js into the comparison module of Add one comparison module with today's rules for ORDER BY, DISTINCT and set operations #3163 as compare.v4.groupConcat and sort with it.
  4. A direct call with the old five arguments (v, s, stage, separator, orderDirection) keeps working and sorts by the value.
  5. With DISTINCT, the first row of each value is kept, with its keys.

What stays the same

  • Without ORDER BY, and with ORDER BY on the aggregated expression itself (written the same way or as 1), every result stays. This includes the localeCompare order of text, NULL values left out, the separator and DISTINCT.
  • Results change only for GROUP_CONCAT(x ORDER BY y) sorts by x, not by y #2658.

Done when

  • A new test file named after this issue covers the example above, DESC, two ORDER BY items, ORDER BY the value itself, ORDER BY 1, NULL keys, SEPARATOR, DISTINCT, GROUP BY with several groups, and a direct call of alasql.aggr.GROUP_CONCAT with five arguments.
  • The full test suite and the CI checks (dialect test, parity check, run-state check, binding check) pass, and the pull request lists every parity difference.

Fixes

Fixes #2658.

Depends on

#2693

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions