Consider the following query encoded through SQLAlchemy.
x_cte = session.query(SomeTable.col1
,OtherTable.col5
) \
.select_from(SomeTable) \
.join(OtherTable, SomeTable.col2 == OtherTable.col3)
.filter(OtherTable.col6 == 34)
.cte(name='x')
subquery = session.query(x_cte
,literal('-1', sqlalchemy.INTEGER).label('quartile')
) \
.filter(x_cte.col1 <= 0)
.union_all(session.query(x_cte
,sqlalchemy.func.ntile(4).over(order_by=x_cte.col1).label('quartile')
)
.filter(x_cte.col1 > 0)
) \
.subquery()
result = session.query(sqlalchemy.func.avg(subquery.columns.x_col1)
,sqlalchemy.func.avg(subquery.columns.x_col5)
,subquery.columns.x_quartile
) \
.group_by(subquery.columns.x_quartile) \
.all()
Sorry for the length, but this seems like my real request. In my real code, I gave a more descriptive name for my CTE, and my CTE has a lot more columns for which I have to calculate the average. (This is also actually a weighted average value, weighted by a column in the CTE.)
"" - . (, . , , .) , subquery.columns.x_[column name]; , SQLAlchemy CTE. , SQLAlchemy CTE , , . CTE, ( ) ; , . ?
Python 2.7.3 SQLAlchemy 0.7.10.