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

How to combine CTE and UNION ALL? #17

Open
peczenyj opened this issue Jan 7, 2025 · 1 comment
Open

How to combine CTE and UNION ALL? #17

peczenyj opened this issue Jan 7, 2025 · 1 comment

Comments

@peczenyj
Copy link

peczenyj commented Jan 7, 2025

Hello

I am trying to use sq to generate dynamic queries and I need to generate a complex combination of WITH (cte) and several queries via UNION ALL

example

WITH … AS foo
SELECTFROM foo … UNION ALL
SELECTFROM foo … UNION ALL

based on the documents I am able to create it in two parts using different object builders but I can create everything at once. Any suggestions?

full example

WITH overlap_table (C1, C2, xxx) AS (
	SELECT T1.C1, T1.C2, table1.xxx
    FROM
        table1 T1,
        table2 T2
    WHERE
        T1.xxx = T2.xxx
)
SELECT C1 AS T1_C1, C2 AS T1_C2, COUNT(xxx) AS overlap
FROM
    overlap_table
GROUP BY (C1, C2)
UNION ALL
SELECT C1 AS T1_C1, NULL AS T1_C2, COUNT(xxx) AS overlap
FROM
    overlap_table
GROUP BY (C1)
UNION ALL
SELECT NULL AS T1_C1, C2 AS T1_C2, COUNT(xxx) AS overlap
FROM
    overlap_table
GROUP BY (C2)
UNION ALL
SELECT NULL AS T1_C1, NULL AS T1_C2, COUNT(xxx) AS overlap
FROM
    overlap_table
GROUP BY ALL
;
@bokwoon95
Copy link
Owner

bokwoon95 commented Jan 7, 2025

Umm can you describe which parts of this query will be dynamic? As you have probably already observed, the built-in CTEs and UNION (ALL) weren't designed to work together so you might have to do a little more hardcoding with Queryf(). It's still possible to add dynamic-ness to Queryf() queries though, I just gotta know which parts of the query will be dynamic.

  • I'm assuming the number of queries to UNION ALL will be dynamic.
  • Are the number of CTEs dynamic?
  • Are the fields being selected dynamic?

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

2 participants