Skip to content

Commit 465ee15

Browse files
committed
Do not add alias to group by
1 parent 525c25e commit 465ee15

File tree

2 files changed

+15
-1
lines changed

2 files changed

+15
-1
lines changed

pypika_tortoise/queries.py

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1662,7 +1662,7 @@ def _group_sql(
16621662
clauses.append(select.get_sql(ctx))
16631663
break
16641664
else:
1665-
clauses.append(field.get_sql(ctx))
1665+
clauses.append(field.get_sql(ctx.copy(with_alias=False)))
16661666

16671667
sql = " GROUP BY {groupby}".format(groupby=",".join(clauses))
16681668

tests/test_selects.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -740,6 +740,20 @@ def test_groupby__multi_with_totals(self):
740740

741741
self.assertEqual('SELECT "foo","bar" FROM "abc" GROUP BY "foo","bar" WITH TOTALS', str(q))
742742

743+
def test_groupby_field_alias_ignored_in_subquery(self):
744+
# When a query with a GROUP BY on a field that has an alias is used as a
745+
# subquery in a FROM clause, the GROUP BY should not include the field
746+
# alias (it should render the field expression only).
747+
inner = Query.from_(self.t).select(self.t.foo).groupby(
748+
self.t.bar.as_("bar_alias")
749+
)
750+
parent = Query.from_(inner).select("*")
751+
752+
self.assertEqual(
753+
'SELECT * FROM (SELECT "foo" FROM "abc" GROUP BY "bar") "sq0"',
754+
str(parent),
755+
)
756+
743757

744758
class HavingTests(unittest.TestCase):
745759
table_abc, table_efg = Tables("abc", "efg")

0 commit comments

Comments
 (0)