SQL vs Ecto optimization/translation help

I am not super experienced at SQL so you may be right, I got some help crafting this SQL query, but the reason for the group_by is that I want to display all the stocks that connect to a particular credit_type together… the current query starts from credit type and credit_type has_many stocks through foods, which is joined through food_groups and food_group_memberships… I guess though I wouldn’t think in terms of aggregations per se, I am kind of aggragating which stocks are reachable from which credit types, and duplicate stocks in each credit type are possible and need to be treated as seperate instances for purposes of this query, if that explains anything… the surrounding context of the Elixir code may make this clearer, but the idea is this is a pure refactor of the function as it exists on master or in the second git sha link in the before version, so that no other code needs to change… Does that help explain/understand?