Repository: tortoise/tortoise-orm (Python)

Issue:
After version 0.16.1 aggregation in aggregate classes works wrong
**Describe the bug**
A clear and concise description of what the bug is.
Post versions of 0.16.1 could cover _ _ aggregateing in annotate method but after 0.16.1 there are no more work as expect (ps. annotate is not root cause it is my example)

**To Reproduce**
Steps to reproduce the behavior, preferaby a small code snippet.

version < 0.16.1
``` python
tournaments = await Tournament.annotate(
    events_participants_count=Count("events__participants")
).filter(id=tournament.id)
print(tournaments.events_participants_count)
```
version \>= 0.16.1
``` python
tournaments = await Tournament.annotate(
    events_participants_count=Count("events__participants")
).filter(id=tournament.id)
print(tournaments.events_participants_count)  # Error
```

exception like this:
```
  File "/storage/tortoise-orm/tortoise/queryset.py", line 604, in _resolve_annotate
    self._join_table_by_field(*join)
  File "/storage/tortoise-orm/tortoise/queryset.py", line 121, in _join_table_by_field
    self.query = self.query.join(join[0], how=JoinType.left_outer).on(join[1])
  File "/root/.pyenv/versions/3.7.6/envs/py37/lib/python3.7/site-packages/pypika/queries.py", line 1391, in on
    self.query.do_join(JoinOn(self.item, self.how, criterion, collate))
  File "/root/.pyenv/versions/3.7.6/envs/py37/lib/python3.7/site-packages/pypika/queries.py", line 969, in do_join
    join.validate(base_tables, self._joins)
  File "/root/.pyenv/versions/3.7.6/envs/py37/lib/python3.7/site-packages/pypika/queries.py", line 1485, in validate
    tables=", ".join(map(str, missing_tables))
pypika.utils.JoinException: Invalid join criterion. One field is required from the joined item and another from the selected table or an existing join.  Found ["event"]
```

**Expected behavior**
A clear and concise description of what you expected to happen.
version < 0.16.1
``` python
tournaments = await Tournament.annotate(
    events_participants_count=Count("events__participants")
).filter(id=tournament.id)
print(tournaments.events_participants_count)
```

**Additional context**
Add any other context about the problem here.
I think culprit commit is `42d85cb84f6684e7364446fc30ec930f0fd60ac4`
(This is not for pressing commiter's responsibility but for more effective bug fix as information)

Lastly, I recommend you to add below test code
``` python
    async def test_nested_aggregation_in_annotation(self):
        tournament = await Tournament.create(name="0")
        await Tournament.create(name="1")
        event = await Event.create(name="2", tournament=tournament)

        team_first = await Team.create(name="First")
        team_second = await Team.create(name="Second")

        await event.participants.add(team_second)
        await event.participants.add(team_first)

        tournaments = await Tournament.annotate(
            events_participants_count=Count("events__participants")
        ).filter(id=tournament.id)
        self.assertEqual(len(tournaments), 1)
        self.assertEqual(tournaments[0].id, tournament.id)
```


Discussion:
Thanks for the detailed bugreport. Indeed that test case passes once we revert that commit.
Thanks for bug reporting! I'll check the point 
I make hotfix PR to fix this bug. @pjongy Plz look that PR :)
Thank you for your quick and accurate work!



Patch:
diff --git a/CHANGELOG.rst b/CHANGELOG.rst
index 4f6b7bcc2..693cd82f5 100644
--- a/CHANGELOG.rst
+++ b/CHANGELOG.rst
@@ -14,6 +14,7 @@ Changelog
 * Default ``values()`` & ``values_list()`` now includes annotations.
 * Annotations over joins now work correctly with ``values()`` & ``values_list()``
 * Ensure ``GROUP BY`` precedes ``HAVING`` to ensure that filtering by aggregates work correctly.
+* Fix bug with join query with aggregation
 
 0.16.1
 ------
diff --git a/tortoise/functions.py b/tortoise/functions.py
index 224b62534..2d88a2ee1 100644
--- a/tortoise/functions.py
+++ b/tortoise/functions.py
@@ -106,7 +106,6 @@ def resolve(self, model: "Type[Model]", table: Table) -> dict:
 
         if isinstance(self.field, str):
             function = self._resolve_field_for_model(model, table, self.field, *self.default_values)
-            function["joins"] = reversed(function["joins"])
             return function
         else:
             field, field_object = F.resolver_arithmetic_expression(model, self.field)


Test patch:
diff --git a/tests/test_aggregation.py b/tests/test_aggregation.py
index a626db6d4..3976e9c2e 100644
--- a/tests/test_aggregation.py
+++ b/tests/test_aggregation.py
@@ -50,6 +50,22 @@ async def test_aggregation(self):
         with self.assertRaisesRegex(ConfigurationError, "name__id not resolvable"):
             await Event.all().annotate(tournament_test_id=Sum("name__id")).first()
 
+    async def test_nested_aggregation_in_annotation(self):
+        tournament = await Tournament.create(name="0")
+        await Tournament.create(name="1")
+        event = await Event.create(name="2", tournament=tournament)
+
+        team_first = await Team.create(name="First")
+        team_second = await Team.create(name="Second")
+
+        await event.participants.add(team_second)
+        await event.participants.add(team_first)
+
+        tournaments = await Tournament.annotate(
+            events_participants_count=Count("events__participants")
+        ).filter(id=tournament.id)
+        self.assertEqual(tournaments[0].events_participants_count, 2)
+
     async def test_aggregation_with_distinct(self):
         tournament = await Tournament.create(name="New Tournament")
         await Event.create(name="Event 1", tournament=tournament)