Order By Association Count within a Dynamically Built Query in Phoenix / Ecto

The standard approach, even in SQL, is to simply repeat the COUNT expression in the ORDER BY as I have already shown:

 ORDER BY COUNT(t.id) DESC;
|> order_by([a,t], desc: count(t.id))

The RDBMS engine is supposed to correlate that expression to the one in the SELECT list without evaluating it twice - so there should be no need to alias the column.

Adding the GROUP BY is the real trick - but it may not be possible to adapt your existing query to tolerating the GROUP BY.