Skip to content

Commit c53a220

Browse files
authored
Merge pull request #37 from tortoise/do-not-add-alias-in-groupby
Do not add alias to group by
2 parents 525c25e + 1ba8546 commit c53a220

File tree

2 files changed

+13
-1
lines changed

2 files changed

+13
-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: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -740,6 +740,18 @@ 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(self.t.bar.as_("bar_alias"))
748+
parent = Query.from_(inner).select("*")
749+
750+
self.assertEqual(
751+
'SELECT * FROM (SELECT "foo" FROM "abc" GROUP BY "bar") "sq0"',
752+
str(parent),
753+
)
754+
743755

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

0 commit comments

Comments
 (0)