Grouping and sorting - column must appear in the GROUP BY issues

Ulitimately that error is neither an Ecto nor an Elixir error but a SQL error.

When learning SQL you don’t start with aggregate queries, it’s considered a more advanced skill and before using them in Ecto it does help considerably to have a good handle on matters in the SQL space.

SELECT
 customer_id,
 SUM (amount)
FROM
 payment
GROUP BY
 customer_id;

The general pattern is that there is an aggregate function (here SUM) and that any column used in the GROUP BY has to appear in the result field list outside of the aggregate function.

So the typical design process is to discover the various (different) SQL queries that are necessary to get you the full range of search options that you require.

Then you decide how to use Ecto to compose the query under the various possible circumstances to arrive at the necessary query for the situation that matches the particular instance of search parameters (an example discussion about composing queries is here).

2 Likes