Skip to content

Group By

Mathias Rangel Wulff edited this page Feb 23, 2016 · 7 revisions

Keyword GROUP BY

Syntax:

    SELECT ... GROUP BY expression, expression...
    SELECT ... GROUP BY CUBE(expression,...) | ROLLUP(expression,...) | GROUPING SETS(expression,...)  

Grouping by columns

    var res = alasql('SELECT * FROM City GROUP BY Contient, Country');

When selecting * the fields not mentioned in the GROUP BY will be given the FIRST(fieldName) value: the value from the very first record in the group from the original data array. Please notice that the value therefore depends solely on the order of the records.

Grouping by expressions

    var res = alasql('SELECT a%2 as isOdd, count(*) as `count` FROM Nums GROUP BY a%2');

Will tell you how many a's are odd and how many are even. See jsFiddle

The example:

    alasql('SELECT projects, FIRST(duration) AS duration, \
        FIRST([path]) AS [path], FIRST(application) AS application  \
        FROM json("timing_output") \
        GROUP BY projects, duration, [path], application \
        ORDER BY duration DESC',[],function(res){
          console.log(res);
    });

Try this example in jsFiddle

Grouping functions

    alasql('SELECT * FROM City GROUP BY ROLLUP(Continent, Country)');

See jsFiddle example for ROLLUP(), CUBE(), and GROUPING SETS().

See also: SELECT, HAVING, CUBE, ROLLUP, [GROUPING SETS](Grouping Sets)

Clone this wiki locally