使用一个CTE引用另一个CTE将SQL转换为SQLAlchemy

时间:2019-05-08 21:26:48

标签: python postgresql sqlalchemy

作为较大查询的一部分,我在SQL中具有以下两个CTE:

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")

我并不完全担心第一个CTE中的多余group_by,但是第二个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),

我试图弄清楚如何在“ from”部分中实际包含cte_one,而不实际将该列添加到cte_two中。我要使用的SQL与some_other_table和cte_one具有唯一性(事物),而我正在生成的SQL与some_other_table和cte_one具有不同特征(thingy),cte_one.my_column_name。

0 个答案:

没有答案