У меня есть следующие два CTE в SQL как часть большего запроса:
with cte_one as (
select
case
when something = 'A' then 'CASE_A'
else 'CASE_B' end as my_column_name
from some_table
group by my_column_name
),
cte_two as (
select distinct(thingy)
from some_other_table, cte_one
where some_conditional = '1'
),
Когда я пытаюсь превратить их в код SQLAlchemy, у меня есть следующее:
cte_one = (
session.query(
variable_that_represents_case_statement.label("my_column_name")
)
.group_by("my_column_name", "column_referenced_in_case_statement")
).cte("cte_one")
# already SQLAlchemy freaked out saying I had to reference the column in the case in my group_by
cte_two = (
session.query(
distinct(model.Some_Other_Table.thingy).label("thingy"),
cte_one
)
.filter(model.Some_Other_Table.some_conditional == 1)
).cte("cte_two")
Я не слишком обеспокоен дополнительным group_by в первом CTE, но второй CTE дает мне выводимый SQL:
cte_two AS
(SELECT DISTINCT some_other_table.thingy AS thingy, cte_one.my_column_name AS my_column_name
FROM some_other_table, cte_one
WHERE some_other_table.some_conditional = %(some_conditional_1)s),
Я пытаюсь выяснить, как на самом деле включить cte_one враздел «от» без добавления этого столбца в cte_two.SQL, из которого я получаю, имеет только отличные (thingy) от some_other_table и cte_one, тогда как SQL, который я создаю, имеет отличные (thingy), cte_one.my_column_name от some_other_table и cte_one.