pypika icon indicating copy to clipboard operation
pypika copied to clipboard

Alias not being specified for complex criteria

Open jcoetzee opened this issue 4 years ago • 2 comments

I'm attempting to use the code snippet below however my alias directives are not being honoured for the middle two SELECT clauses (Q2 and Q3) while the are being specified for Q1 and Q4 (which are simple less than or greater than comparisons). The function returns without error so it's failing silently. Am I specifying something incorrectly? I also tried with Criterion.all([]) with the same result. Python 3.9.0 and PyPika 0.44.0

from pypika import MySQLQuery, Table, functions
metrics = Table('metrics')
q = MySQLQuery.from_(metrics).select(
                functions.Count('1').as_('count'),
                (metrics.date < "2020-04-01 00:00:00").as_('Q1'),
                ((metrics.date >= "2020-04-01 00:00:00") & (metrics.date < "2020-07-01 00:00:00")).as_('Q2'),
                ((metrics.date >= "2020-07-01 00:00:00") & (metrics.date < "2020-10-01 00:00:00")).as_('Q3'),
                (metrics.date >= "2020-10-01 00:00:00").as_('Q4')
            ).where(metrics.date >= "2020-01-01 00:00:00").groupby("Q1", "Q2", "Q3", "Q4")
print(q.get_sql())

Output:

SELECT COUNT('1') `count`,`date`<'2020-04-01 00:00:00' Q1,`date`>='2020-04-01 00:00:00' AND `date`<'2020-07-01 00:00:00',`date`>='2020-07-01 00:00:00' AND `date`<'2020-10-01 00:00:00',`date`>='2020-10-01 00:00:00' Q4 FROM `metrics` WHERE `date`>='2020-01-01 00:00:00' GROUP BY `Q1`,`Q2`,`Q3`,`Q4`

jcoetzee avatar Nov 11 '20 10:11 jcoetzee

I am seeing a similar issue. I am expecting this to give a single column named "in_the_future", but the alias is not coming out in the generated SQL.

from pypika import Table, Query
from pypika.functions import Now, Coalesce

table = Table('table')

query = Query.from_(table).select(
    (table.some_boolean_column | Coalesce(table.timestamp > Now(), False)).as_('in_the_future'),
)

print(query.get_sql())

Expected output:

SELECT "some_boolean_column" OR COALESCE("timestamp">NOW(),false) in_the_future FROM "table"

Actual output:

SELECT "some_boolean_column" OR COALESCE("timestamp">NOW(),false) FROM "table"

jtetrault avatar Feb 26 '21 17:02 jtetrault

see https://github.com/kayak/pypika/pull/735

Ga68 avatar Jul 07 '23 13:07 Ga68