From 1ba8546894671e5495ca1483dd261c3ee8332b63 Mon Sep 17 00:00:00 2001 From: Henadzi Tsaryk Date: Sun, 23 Nov 2025 17:20:35 +0100 Subject: [PATCH] Do not add alias to group by --- pypika_tortoise/queries.py | 2 +- tests/test_selects.py | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/pypika_tortoise/queries.py b/pypika_tortoise/queries.py index 34091de..7d49adf 100644 --- a/pypika_tortoise/queries.py +++ b/pypika_tortoise/queries.py @@ -1662,7 +1662,7 @@ def _group_sql( clauses.append(select.get_sql(ctx)) break else: - clauses.append(field.get_sql(ctx)) + clauses.append(field.get_sql(ctx.copy(with_alias=False))) sql = " GROUP BY {groupby}".format(groupby=",".join(clauses)) diff --git a/tests/test_selects.py b/tests/test_selects.py index 8176e10..8f52c67 100644 --- a/tests/test_selects.py +++ b/tests/test_selects.py @@ -740,6 +740,18 @@ def test_groupby__multi_with_totals(self): self.assertEqual('SELECT "foo","bar" FROM "abc" GROUP BY "foo","bar" WITH TOTALS', str(q)) + def test_groupby_field_alias_ignored_in_subquery(self): + # When a query with a GROUP BY on a field that has an alias is used as a + # subquery in a FROM clause, the GROUP BY should not include the field + # alias (it should render the field expression only). + inner = Query.from_(self.t).select(self.t.foo).groupby(self.t.bar.as_("bar_alias")) + parent = Query.from_(inner).select("*") + + self.assertEqual( + 'SELECT * FROM (SELECT "foo" FROM "abc" GROUP BY "bar") "sq0"', + str(parent), + ) + class HavingTests(unittest.TestCase): table_abc, table_efg = Tables("abc", "efg")