Skip to content

Commit

Permalink
fix!: handle unnesting groups closes #3056 (#3058)
Browse files Browse the repository at this point in the history
  • Loading branch information
tobymao committed Feb 29, 2024
1 parent d587669 commit 08bafbd
Show file tree
Hide file tree
Showing 3 changed files with 29 additions and 2 deletions.
14 changes: 13 additions & 1 deletion sqlglot/optimizer/unnest_subqueries.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,8 +94,20 @@ def unnest(select, parent_select, next_alias_name):
else:
_replace(predicate, join_key_not_null)

group = select.args.get("group")

if group:
if {value.this} != set(group.expressions):
select = (
exp.select(exp.column(value.alias, "_q"))
.from_(select.subquery("_q", copy=False), copy=False)
.group_by(exp.column(value.alias, "_q"), copy=False)
)
else:
select = select.group_by(value.this, copy=False)

parent_select.join(
select.group_by(value.this, copy=False),
select,
on=column.eq(join_key),
join_type="LEFT",
join_alias=alias,
Expand Down
1 change: 0 additions & 1 deletion tests/fixtures/optimizer/tpc-h/tpc-h.sql
Original file line number Diff line number Diff line change
Expand Up @@ -1047,7 +1047,6 @@ WITH "_u_0" AS (
"lineitem"."l_orderkey" AS "l_orderkey"
FROM "lineitem" AS "lineitem"
GROUP BY
"lineitem"."l_orderkey",
"lineitem"."l_orderkey"
HAVING
SUM("lineitem"."l_quantity") > 300
Expand Down
16 changes: 16 additions & 0 deletions tests/fixtures/optimizer/unnest_subqueries.sql
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ WHERE
AND x.a > ALL (SELECT y.c FROM y WHERE y.a = x.a)
AND x.a > (SELECT COUNT(*) as d FROM y WHERE y.a = x.a)
AND x.a = SUM(SELECT 1) -- invalid statement left alone
AND x.a IN (SELECT max(y.b) AS b FROM y GROUP BY y.a)
;
SELECT
*
Expand Down Expand Up @@ -155,6 +156,20 @@ LEFT JOIN (
y.a
) AS _u_21
ON _u_21._u_22 = x.a
LEFT JOIN (
SELECT
_q.b
FROM (
SELECT
MAX(y.b) AS b
FROM y
GROUP BY
y.a
) AS _q
GROUP BY
_q.b
) AS _u_24
ON x.a = _u_24.b
WHERE
x.a = _u_0.a
AND NOT _u_1.a IS NULL
Expand Down Expand Up @@ -212,6 +227,7 @@ WHERE
AND x.a > COALESCE(_u_21.d, 0)
AND x.a = SUM(SELECT
1) /* invalid statement left alone */
AND NOT _u_24.b IS NULL
;
SELECT
CAST((
Expand Down

0 comments on commit 08bafbd

Please sign in to comment.