Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handle AliasedQuery in backend during with statement #784

Open
wd60622 opened this issue Jan 18, 2024 · 0 comments
Open

Handle AliasedQuery in backend during with statement #784

wd60622 opened this issue Jan 18, 2024 · 0 comments

Comments

@wd60622
Copy link
Contributor

wd60622 commented Jan 18, 2024

In order to create a CTE query like this one

-- Query from https://learnsql.com/blog/what-is-common-table-expression/
WITH highest AS (
  SELECT
    branch,
    date,
    MAX(unit_price) AS highest_price
  FROM sales
  GROUP BY branch, date
)
SELECT
  sales.*,
  h.highest_price
FROM sales
JOIN highest h
  ON sales.branch = h.branch
    AND sales.date = h.date

an AliasedQuery needs to be created with the name needed to be passed twice (into AliasedQuery and in with_)

sales = Table("sales")

highest_query = (
    Query
    .from_(sales)
    .select(sales.branch, sales.date, fn.Max(sales.unit_price).as_("highest_price"))
    .groupby(sales.branch, sales.date)
)

# Create an AliasedQuery 
highest_alias = "highest"
highest = AliasedQuery(highest_alias)

join_condition = (
    (sales.branch == highest.branch) 
    & (sales.date == highest.date)
)

query = (
    Query
    .with_(highest_query, highest_alias)
    .from_(sales)
    .join(highest)
    .on(join_condition)
    .select(sales.star, highest.highest_sales)
)

However, I think this syntax would be a lot easier to work with.

sales = Table("sales")
highest = (
    Query
    .from_(sales)
    .select("branch", "date", fn.Max("unit_price").as_("highest_price"))
    .groupby("branch", "date")
).as_("highest")

query = (
    Query
    .with_(highest)
    .from_(sales)
    .join(highest)
    .on(join_condition)
    .select(sales.star, highest.highest_price)
)

Where a QueryBuilder could be aliased which would signify it can be used liked a AliasedQuery

@wd60622 wd60622 changed the title Handles AliasedQuery in backend Handle AliasedQuery in backend during with statement Jan 18, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant