Back to Grouping & Aggregation

qSQL · Grouping & Aggregation · Practice Question

Find the Symbol With the Most Appearances

Sign in to track your progress

Question

Given:

t:([] sym:100?`A`B`C)

Write a single expression that returns the sym value that appears most often in the table.

Expected result (will vary due to random data):

`C

Solution

first exec sym from desc select count i by sym from t

Explanation

Working from the inside out:

select count i by sym from t groups the table by sym and counts the rows in each group. i is the built-in row-index column — count i is the idiomatic way to count rows per group:

sym| x
---| --
A  | 31
B  | 36
C  | 33

desc sorts the keyed table by its value column, descending, putting the most frequent sym first:

sym| x
---| --
B  | 36
C  | 33
A  | 31

exec sym from extracts the sym key column as a plain list (not a table):

`B`C`A

first takes the first element — the most frequent sym:

`B

Why exec, not select?

select sym from ... would return a single-column table:

sym
---
B
C
A

exec sym from ... returns a plain list B C A, which first can index directly. With select, you would need an extra step to pull the column out, such as first (select sym from ...)`sym, which is longer and less readable.

Alternative

first key desc count each group t`sym

group t`sym returns a dictionary mapping each sym to its row indices; count each counts the indices; desc sorts descending; first key takes the key of the top entry.