SQLAlchemy Select 来自两个子查询的连接

SQLAlchemy Select from Join of two Subqueries

需要帮助将此 SQL 查询转换为 SQLAlchemy:

select 
    COALESCE(DATE_1,DATE_2) as DATE_COMPLETE,
    QUESTIONS_CNT,
    ANSWERS_CNT
    from (
        (select DATE as DATE_1,
         count(distinct QUESTIONS) as  QUESTIONS_CNT
            from GUEST_USERS    
                where LOCATION like '%TEXAS%'
                and DATE = '2021-08-08'
                    group by DATE 
        ) temp1
        full join 
        (select DATE as DATE_2,
         count(distinct ANSWERS) as  ANSWERS_CNT
            from USERS 
                where LOCATION like '%TEXAS%'
                and DATE = '2021-08-08'
                    group by DATE 
        ) temp2 
        on temp1.DATE_1=temp2.DATE_2
    )

主要是在努力连接两个子查询。我试过这个(只是为了 SQL 的连接部分):

query1 = db.session.query(
    GUEST_USERS.DATE_WEEK_START.label("DATE_1"),
    func.count(GUEST_USERS.QUESTIONS).label("QUESTIONS_CNT")
).filter(
    GUEST_USERS.LOCATION.like("%TEXAS%"),
    GUEST_USERS.DATE == "2021-08-08"
).group_by(GUEST_USERS.DATE)

query2 = db_session_stg.query(
    USERS.DATE.label("DATE_2"),
    func.count(USERS.ANSWERS).label("ANSWERS_CNT")
).filter(
    USERS.LOCATION.like("%TEXAS%"),
    USERS.DATE == "2021-08-08"
).group_by(USERS.DATE)

sq2 = query2.subquery()

query1_results = query1.join(
        sq2,
        sq2.c.DATE_2 == GUEST_USERS.DATE)
    ).all()

在此输出中,我仅收到 DATE_1 列和 QUESTIONS_CNT 列。知道为什么子查询的选定输出没有在结果中返回吗?

不确定这是否是最佳解决方案,但这就是我让它工作的方式。基本上使用 3 个子查询。

query1 = db.session.query(
    GUEST_USERS.DATE_WEEK_START.label("DATE_1"),
    func.count(GUEST_USERS.QUESTIONS).label("QUESTIONS_CNT")
).filter(
    GUEST_USERS.LOCATION.like("%TEXAS%"),
    GUEST_USERS.DATE == "2021-08-08"
).group_by(GUEST_USERS.DATE)

query2 = db_session_stg.query(
    USERS.DATE.label("DATE_2"),
    func.count(USERS.ANSWERS).label("ANSWERS_CNT")
).filter(
    USERS.LOCATION.like("%TEXAS%"),
    USERS.DATE == "2021-08-08"
).group_by(USERS.DATE)

sq1 = query1.subquery()
sq2 = query2.subquery()

query3 = db.session.query(sq1, sq2).join(
    sq2,
    sq2.c.DATE_2 == sq1.c.DATE_1)
sq3 = query3.subquery()

query4 = db.session.query(
    func.coalesce(
        sq3.c.DATE_1, sq3.c.DATE_2),
    sq3.c.QUESTIONS_CNT,
    sq3.c.ANSWERS_CNT
)
results = query4.all()