Skip to content

Commit 9f169ab

Browse files
Fix(redshift): support APPROXIMATE PERCENTILE_DISC round-trip (#7585)
1 parent b3fa159 commit 9f169ab

3 files changed

Lines changed: 20 additions & 1 deletion

File tree

sqlglot/generators/redshift.py

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -270,6 +270,14 @@ class RedshiftGenerator(PostgresGenerator):
270270
"without",
271271
}
272272

273+
def approxquantile_sql(self, expression: exp.ApproxQuantile) -> str:
274+
return "APPROXIMATE " + self.sql(
275+
exp.WithinGroup(
276+
this=exp.PercentileDisc(this=expression.args["quantile"]),
277+
expression=exp.Order(expressions=[exp.Ordered(this=expression.this)]),
278+
)
279+
)
280+
273281
def unnest_sql(self, expression: exp.Unnest) -> str:
274282
args = expression.expressions
275283
num_args = len(args)

sqlglot/parsers/redshift.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -96,12 +96,20 @@ def _parse_convert(self, strict: bool, safe: bool | None = None) -> exp.Expr | N
9696
this = self._parse_bitwise()
9797
return self.expression(exp.TryCast(this=this, to=to, safe=safe))
9898

99-
def _parse_approximate_count(self) -> exp.ApproxDistinct | None:
99+
def _parse_approximate_count(self) -> exp.ApproxDistinct | exp.ApproxQuantile | None:
100100
index = self._index - 1
101101
func = self._parse_function()
102102

103103
if isinstance(func, exp.Count) and isinstance(func.this, exp.Distinct):
104104
return self.expression(exp.ApproxDistinct(this=seq_get(func.this.expressions, 0)))
105+
if isinstance(func, exp.WithinGroup) and isinstance(func.this, exp.PercentileDisc):
106+
ordered = seq_get(func.expression.expressions, 0)
107+
return self.expression(
108+
exp.ApproxQuantile(
109+
this=ordered.this if ordered else None,
110+
quantile=func.this.this,
111+
)
112+
)
105113
self._retreat(index)
106114
return None
107115

tests/dialects/test_redshift.py

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -362,6 +362,9 @@ def test_identity(self):
362362
self.validate_identity("'%' SIMILAR TO '^%' ESCAPE '^'")
363363
self.validate_identity("CREATE TABLE datetable (start_date DATE, end_date DATE)")
364364
self.validate_identity("SELECT APPROXIMATE AS y")
365+
self.validate_identity(
366+
"SELECT APPROXIMATE PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY totalprice)"
367+
)
365368
self.validate_identity("CREATE TABLE t (c BIGINT IDENTITY(0, 1))")
366369
self.validate_identity(
367370
"COPY test_staging_tbl FROM 's3://your/bucket/prefix/here' IAM_ROLE default FORMAT AS AVRO 'auto'"

0 commit comments

Comments
 (0)