简体   繁体   中英

SQLAlchemy Select from Join of two Subqueries

Need help translating this SQL query into 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
    )

Mainly struggling with the join of the two subqueries. I've tried this (just for the join part of the 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()

In this output I receive only the DATE_1 column and the QUESTIONS_CNT columns. Any idea why the selected output from the subquery is not being returned in the result?

Not sure if this is the best solution but this is how I got it to work. Using 3 subqueries essentially.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM